Draft
[WIP]feat(moe): add MoonEP backend #7
&NewgateAdd on 15 days ago
[WIP]feat(moe): add MoonEP backend #7
Draft
Merged fromrefactor/moonep-runtime-coordinationintocore_r0.18.0
Total: 982 files changed+19618-6096
| @@ -0,0 +1 @@ | |||
| 1 | +mindspeed/ops/gmm.py -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol | ||
| @@ -0,0 +1,486 @@ | |||
| 1 | +project: Ascend/MindSpeed | ||
| 2 | +directories: | ||
| 3 | + - path: "./mindspeed/" | ||
| 4 | + type: source | ||
| 5 | + - path: "./mindspeed/auto_settings/module/black/patch/experts.py" | ||
| 6 | + type: upstream | ||
| 7 | + - path: "./mindspeed/checkpointing.py" | ||
| 8 | + type: upstream | ||
| 9 | + - path: "./mindspeed/core/context_parallel/get_batch_utils.py" | ||
| 10 | + type: upstream | ||
| 11 | + - path: "./mindspeed/core/context_parallel/ulysses_context_parallel/ulysses_context_parallel.py" | ||
| 12 | + type: upstream | ||
| 13 | + - path: "./mindspeed/core/context_parallel/utils.py" | ||
| 14 | + type: upstream | ||
| 15 | + - path: "./mindspeed/core/data_parallel/async_log_allreduce.py" | ||
| 16 | + type: upstream | ||
| 17 | + - path: "./mindspeed/core/data_parallel/distributed_data_parallel.py" | ||
| 18 | + type: upstream | ||
| 19 | + - path: "./mindspeed/core/datasets/gpt_dataset.py" | ||
| 20 | + type: upstream | ||
| 21 | + - path: "./mindspeed/core/distributed/buffer_pad/adaptor.py" | ||
| 22 | + type: upstream | ||
| 23 | + - path: "./mindspeed/core/distributed/custom_fsdp/param_and_grad_buffer.py" | ||
| 24 | + type: upstream | ||
| 25 | + - path: "./mindspeed/core/distributed/layerzero/config.py" | ||
| 26 | + type: upstream | ||
| 27 | + - path: "./mindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/clip.py" | ||
| 28 | + type: upstream | ||
| 29 | + - path: "./mindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/misc.py" | ||
| 30 | + type: upstream | ||
| 31 | + - path: "./mindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/sharded_grad_scaler.py" | ||
| 32 | + type: upstream | ||
| 33 | + - path: "./mindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/zero.py" | ||
| 34 | + type: upstream | ||
| 35 | + - path: "./mindspeed/core/distributed/layerzero/runtime/_forward.py" | ||
| 36 | + type: upstream | ||
| 37 | + - path: "./mindspeed/core/distributed/layerzero/runtime/_initialize.py" | ||
| 38 | + type: upstream | ||
| 39 | + - path: "./mindspeed/core/distributed/layerzero/runtime/_root_forward.py" | ||
| 40 | + type: upstream | ||
| 41 | + - path: "./mindspeed/core/distributed/layerzero/runtime/_shard.py" | ||
| 42 | + type: upstream | ||
| 43 | + - path: "./mindspeed/core/distributed/layerzero/runtime/_utils.py" | ||
| 44 | + type: upstream | ||
| 45 | + - path: "./mindspeed/core/distributed/layerzero/runtime/hook.py" | ||
| 46 | + type: upstream | ||
| 47 | + - path: "./mindspeed/core/distributed/layerzero/state/mga_checkpoint.py" | ||
| 48 | + type: upstream | ||
| 49 | + - path: "./mindspeed/core/distributed/layerzero/state/optim_state.py" | ||
| 50 | + type: upstream | ||
| 51 | + - path: "./mindspeed/core/distributed/layerzero/state/scripts/convert_to_megatron.py" | ||
| 52 | + type: upstream | ||
| 53 | + - path: "./mindspeed/core/distributed/layerzero/state/state_dict.py" | ||
| 54 | + type: upstream | ||
| 55 | + - path: "./mindspeed/core/distributed/layerzero/zero3/_common_utils.py" | ||
| 56 | + type: upstream | ||
| 57 | + - path: "./mindspeed/core/distributed/layerzero/zero3/_exec_order_utils.py" | ||
| 58 | + type: upstream | ||
| 59 | + - path: "./mindspeed/core/distributed/layerzero/zero3/_init_utils.py" | ||
| 60 | + type: upstream | ||
| 61 | + - path: "./mindspeed/core/distributed/layerzero/zero3/_traversal_utils.py" | ||
| 62 | + type: upstream | ||
| 63 | + - path: "./mindspeed/core/distributed/layerzero/zero3/_wrap_utils.py" | ||
| 64 | + type: upstream | ||
| 65 | + - path: "./mindspeed/core/distributed/layerzero/zero3/api.py" | ||
| 66 | + type: upstream | ||
| 67 | + - path: "./mindspeed/core/distributed/layerzero/zero3/flat_param.py" | ||
| 68 | + type: upstream | ||
| 69 | + - path: "./mindspeed/core/distributed/layerzero/zero3/fsdp.py" | ||
| 70 | + type: upstream | ||
| 71 | + - path: "./mindspeed/core/distributed/layerzero/zero3/wrap.py" | ||
| 72 | + type: upstream | ||
| 73 | + - path: "./mindspeed/core/distributed/param_and_grad_buffer.py" | ||
| 74 | + type: upstream | ||
| 75 | + - path: "./mindspeed/core/distributed/reset_bucket_group_order_feature/distributed_data_parallel.py" | ||
| 76 | + type: upstream | ||
| 77 | + - path: "./mindspeed/core/distributed/torch_fully_sharded_data_parallel/checkpointing.py" | ||
| 78 | + type: upstream | ||
| 79 | + - path: "./mindspeed/core/distributed/torch_fully_sharded_data_parallel/torch_fully_sharded_data_parallel_adaptor.py" | ||
| 80 | + type: upstream | ||
| 81 | + - path: "./mindspeed/core/distributed/torch_fully_sharded_data_parallel/training.py" | ||
| 82 | + type: upstream | ||
| 83 | + - path: "./mindspeed/core/distributed/torch_fully_sharded_data_parallel/utils.py" | ||
| 84 | + type: upstream | ||
| 85 | + - path: "./mindspeed/core/fp8_checkpoint.py" | ||
| 86 | + type: upstream | ||
| 87 | + - path: "./mindspeed/core/fp8_utils.py" | ||
| 88 | + type: upstream | ||
| 89 | + - path: "./mindspeed/core/fusions/fused_moe_permute.py" | ||
| 90 | + type: upstream | ||
| 91 | + - path: "./mindspeed/core/fusions/fused_rms_norm.py" | ||
| 92 | + type: upstream | ||
| 93 | + - path: "./mindspeed/core/fusions/fused_rope.py" | ||
| 94 | + type: upstream | ||
| 95 | + - path: "./mindspeed/core/megatron_basic/get_megatron_optimizer.py" | ||
| 96 | + type: upstream | ||
| 97 | + - path: "./mindspeed/core/megatron_basic/megatron_basic.py" | ||
| 98 | + type: upstream | ||
| 99 | + - path: "./mindspeed/core/memory/common.py" | ||
| 100 | + type: upstream | ||
| 101 | + - path: "./mindspeed/core/memory/compress/compress_optimizer.py" | ||
| 102 | + type: upstream | ||
| 103 | + - path: "./mindspeed/core/memory/compress_dense/adaptor.py" | ||
| 104 | + type: upstream | ||
| 105 | + - path: "./mindspeed/core/memory/compress_dense/mlp_forward.py" | ||
| 106 | + type: upstream | ||
| 107 | + - path: "./mindspeed/core/memory/recompute/activation/activation_recompute_forward.py" | ||
| 108 | + type: upstream | ||
| 109 | + - path: "./mindspeed/core/memory/recompute/activation/adaptor.py" | ||
| 110 | + type: upstream | ||
| 111 | + - path: "./mindspeed/core/memory/recompute/norm/adaptor.py" | ||
| 112 | + type: upstream | ||
| 113 | + - path: "./mindspeed/core/memory/reuse_param/adaptor.py" | ||
| 114 | + type: upstream | ||
| 115 | + - path: "./mindspeed/core/memory/reuse_param/reuse_distrib_optimizer.py" | ||
| 116 | + type: upstream | ||
| 117 | + - path: "./mindspeed/core/models/common/embeddings/language_model_embedding.py" | ||
| 118 | + type: upstream | ||
| 119 | + - path: "./mindspeed/core/models/common/embeddings/rotary_pos_embedding.py" | ||
| 120 | + type: upstream | ||
| 121 | + - path: "./mindspeed/core/models/gpt/gpt_model.py" | ||
| 122 | + type: upstream | ||
| 123 | + - path: "./mindspeed/core/models/multimodal/llava_model.py" | ||
| 124 | + type: upstream | ||
| 125 | + - path: "./mindspeed/core/moe/permutation.py" | ||
| 126 | + type: upstream | ||
| 127 | + - path: "./mindspeed/core/multi_modal/dist_train/dist_parallel_state.py" | ||
| 128 | + type: upstream | ||
| 129 | + - path: "./mindspeed/core/multi_modal/dist_train/dist_schedules.py" | ||
| 130 | + type: upstream | ||
| 131 | + - path: "./mindspeed/core/multi_modal/dist_train/inner_data_parallel.py" | ||
| 132 | + type: upstream | ||
| 133 | + - path: "./mindspeed/core/optimizer/distrib_optimizer.py" | ||
| 134 | + type: upstream | ||
| 135 | + - path: "./mindspeed/core/optimizer/fix_duplicate_allgather.py" | ||
| 136 | + type: upstream | ||
| 137 | + - path: "./mindspeed/core/optimizer/fused_ema_adamw/adaptor.py" | ||
| 138 | + type: upstream | ||
| 139 | + - path: "./mindspeed/core/optimizer/low_precision/finalize_model_grads.py" | ||
| 140 | + type: upstream | ||
| 141 | + - path: "./mindspeed/core/optimizer/low_precision/quant_distributed_hooks.py" | ||
| 142 | + type: upstream | ||
| 143 | + - path: "./mindspeed/core/optimizer/low_precision/quant_grad_clip.py" | ||
| 144 | + type: upstream | ||
| 145 | + - path: "./mindspeed/core/optimizer/muon/adaptor.py" | ||
| 146 | + type: upstream | ||
| 147 | + - path: "./mindspeed/core/optimizer/muon/checkpointing.py" | ||
| 148 | + type: upstream | ||
| 149 | + - path: "./mindspeed/core/optimizer/muon/emerging_optimizers.py" | ||
| 150 | + type: upstream | ||
| 151 | + - path: "./mindspeed/core/optimizer/muon/layer_wise_optimizer.py" | ||
| 152 | + type: upstream | ||
| 153 | + - path: "./mindspeed/core/optimizer/muon/muon.py" | ||
| 154 | + type: upstream | ||
| 155 | + - path: "./mindspeed/core/optimizer/muon/muon_utils.py" | ||
| 156 | + type: upstream | ||
| 157 | + - path: "./mindspeed/core/optimizer/muon/optimizer_config.py" | ||
| 158 | + type: upstream | ||
| 159 | + - path: "./mindspeed/core/optimizer/muon/optimizer_param_scheduler.py" | ||
| 160 | + type: upstream | ||
| 161 | + - path: "./mindspeed/core/optimizer/muon/orthogonalized_optimizer.py" | ||
| 162 | + type: upstream | ||
| 163 | + - path: "./mindspeed/core/optimizer/muon/param_and_grad_buffer.py" | ||
| 164 | + type: upstream | ||
| 165 | + - path: "./mindspeed/core/optimizer/muon/utils.py" | ||
| 166 | + type: upstream | ||
| 167 | + - path: "./mindspeed/core/optimizer/swap_muon/swap_muon.py" | ||
| 168 | + type: upstream | ||
| 169 | + - path: "./mindspeed/core/optimizer/swap_optimizer/swap_optimizer.py" | ||
| 170 | + type: upstream | ||
| 171 | + - path: "./mindspeed/core/optimizer/virtual_optimizer/virtual_adam.py" | ||
| 172 | + type: upstream | ||
| 173 | + - path: "./mindspeed/core/parallel_state.py" | ||
| 174 | + type: upstream | ||
| 175 | + - path: "./mindspeed/core/performance/auto_pipeline_perf/schedules.py" | ||
| 176 | + type: upstream | ||
| 177 | + - path: "./mindspeed/core/pipeline_parallel/dualpipev/dualpipev_chunks.py" | ||
| 178 | + type: upstream | ||
| 179 | + - path: "./mindspeed/core/pipeline_parallel/dualpipev/dualpipev_schedules.py" | ||
| 180 | + type: upstream | ||
| 181 | + - path: "./mindspeed/core/pipeline_parallel/dualpipev/mtp_utils.py" | ||
| 182 | + type: upstream | ||
| 183 | + - path: "./mindspeed/core/pipeline_parallel/flexible_schedules.py" | ||
| 184 | + type: upstream | ||
| 185 | + - path: "./mindspeed/core/pipeline_parallel/multi_parameter/adaptor.py" | ||
| 186 | + type: upstream | ||
| 187 | + - path: "./mindspeed/core/pipeline_parallel/multi_parameter/common.py" | ||
| 188 | + type: upstream | ||
| 189 | + - path: "./mindspeed/core/pipeline_parallel/multi_parameter/communication.py" | ||
| 190 | + type: upstream | ||
| 191 | + - path: "./mindspeed/core/pipeline_parallel/multiparameter_schedules.py" | ||
| 192 | + type: upstream | ||
| 193 | + - path: "./mindspeed/core/pipeline_parallel/noop_layers/adaptor.py" | ||
| 194 | + type: upstream | ||
| 195 | + - path: "./mindspeed/core/pipeline_parallel/noop_layers/moe_metrics_tracker.py" | ||
| 196 | + type: upstream | ||
| 197 | + - path: "./mindspeed/core/pipeline_parallel/optimize_send_recv_comm/adaptor.py" | ||
| 198 | + type: upstream | ||
| 199 | + - path: "./mindspeed/core/pipeline_parallel/optimize_send_recv_comm/parallel_state.py" | ||
| 200 | + type: upstream | ||
| 201 | + - path: "./mindspeed/core/pipeline_parallel/p2p_communication.py" | ||
| 202 | + type: upstream | ||
| 203 | + - path: "./mindspeed/core/pipeline_parallel/pipeline_model_parallel_layout/adaptor.py" | ||
| 204 | + type: upstream | ||
| 205 | + - path: "./mindspeed/core/pipeline_parallel/pipeline_model_parallel_layout/layout.py" | ||
| 206 | + type: upstream | ||
| 207 | + - path: "./mindspeed/core/pipeline_parallel/ripipe_schedules.py" | ||
| 208 | + type: upstream | ||
| 209 | + - path: "./mindspeed/core/pipeline_parallel/schedules.py" | ||
| 210 | + type: upstream | ||
| 211 | + - path: "./mindspeed/core/pipeline_parallel/variable_seq_length/adaptor.py" | ||
| 212 | + type: upstream | ||
| 213 | + - path: "./mindspeed/core/pipeline_parallel/variable_seq_length/common.py" | ||
| 214 | + type: upstream | ||
| 215 | + - path: "./mindspeed/core/pipeline_parallel/variable_seq_length/communicate.py" | ||
| 216 | + type: upstream | ||
| 217 | + - path: "./mindspeed/core/qat/layers.py" | ||
| 218 | + type: upstream | ||
| 219 | + - path: "./mindspeed/core/qos/adaptor.py" | ||
| 220 | + type: upstream | ||
| 221 | + - path: "./mindspeed/core/qos/domain_info.py" | ||
| 222 | + type: upstream | ||
| 223 | + - path: "./mindspeed/core/ssm/gated_delta_net.py" | ||
| 224 | + type: upstream | ||
| 225 | + - path: "./mindspeed/core/ssm/triton_chunk_gated_delta_rule.py" | ||
| 226 | + type: upstream | ||
| 227 | + - path: "./mindspeed/core/tensor_parallel/ascend_turbo/initialize.py" | ||
| 228 | + type: upstream | ||
| 229 | + - path: "./mindspeed/core/tensor_parallel/coc_feature/coc_column_parallel_linear.py" | ||
| 230 | + type: upstream | ||
| 231 | + - path: "./mindspeed/core/tensor_parallel/coc_feature/coc_row_parallel_linear.py" | ||
| 232 | + type: upstream | ||
| 233 | + - path: "./mindspeed/core/tensor_parallel/layers.py" | ||
| 234 | + type: upstream | ||
| 235 | + - path: "./mindspeed/core/tensor_parallel/mapping.py" | ||
| 236 | + type: upstream | ||
| 237 | + - path: "./mindspeed/core/tensor_parallel/mc2_feature/adaptor.py" | ||
| 238 | + type: upstream | ||
| 239 | + - path: "./mindspeed/core/tensor_parallel/mc2_feature/linear_function.py" | ||
| 240 | + type: upstream | ||
| 241 | + - path: "./mindspeed/core/tensor_parallel/mc2_feature/mc2_column_parallel_linear.py" | ||
| 242 | + type: upstream | ||
| 243 | + - path: "./mindspeed/core/tensor_parallel/mc2_feature/mc2_row_parallel_linear.py" | ||
| 244 | + type: upstream | ||
| 245 | + - path: "./mindspeed/core/tensor_parallel/random.py" | ||
| 246 | + type: upstream | ||
| 247 | + - path: "./mindspeed/core/tensor_parallel/tp_2d/schedules_2d.py" | ||
| 248 | + type: upstream | ||
| 249 | + - path: "./mindspeed/core/tensor_parallel/tp_2d/transformer_config.py" | ||
| 250 | + type: upstream | ||
| 251 | + - path: "./mindspeed/core/tensor_parallel/unaligned_layers/adaptor.py" | ||
| 252 | + type: upstream | ||
| 253 | + - path: "./mindspeed/core/tensor_parallel/unaligned_layers/unaligned_column_parallel_linear.py" | ||
| 254 | + type: upstream | ||
| 255 | + - path: "./mindspeed/core/tensor_parallel/unaligned_layers/unaligned_row_parallel_linear.py" | ||
| 256 | + type: upstream | ||
| 257 | + - path: "./mindspeed/core/tensor_parallel/unaligned_layers/unaligned_utils.py" | ||
| 258 | + type: upstream | ||
| 259 | + - path: "./mindspeed/core/tensor_parallel/vocab_parallel/adaptor.py" | ||
| 260 | + type: upstream | ||
| 261 | + - path: "./mindspeed/core/tensor_parallel/vocab_parallel/vocab_parallel.py" | ||
| 262 | + type: upstream | ||
| 263 | + - path: "./mindspeed/core/training.py" | ||
| 264 | + type: upstream | ||
| 265 | + - path: "./mindspeed/core/transformer/attention.py" | ||
| 266 | + type: upstream | ||
| 267 | + - path: "./mindspeed/core/transformer/dot_product_attention.py" | ||
| 268 | + type: upstream | ||
| 269 | + - path: "./mindspeed/core/transformer/experimental_attention_variant/dsa_matrix_absorption.py" | ||
| 270 | + type: upstream | ||
| 271 | + - path: "./mindspeed/core/transformer/experimental_attention_variant/dsa_npu_fused.py" | ||
| 272 | + type: upstream | ||
| 273 | + - path: "./mindspeed/core/transformer/flash_attention/alibi/adaptor.py" | ||
| 274 | + type: upstream | ||
| 275 | + - path: "./mindspeed/core/transformer/flash_attention/alibi/alibi.py" | ||
| 276 | + type: upstream | ||
| 277 | + - path: "./mindspeed/core/transformer/flash_attention/alibi/alibi_utils.py" | ||
| 278 | + type: upstream | ||
| 279 | + - path: "./mindspeed/core/transformer/flash_attention/alibi/dot_product_attention.py" | ||
| 280 | + type: upstream | ||
| 281 | + - path: "./mindspeed/core/transformer/flash_attention/flash_attention/adaptor.py" | ||
| 282 | + type: upstream | ||
| 283 | + - path: "./mindspeed/core/transformer/flash_attention/generate_mask/adaptor.py" | ||
| 284 | + type: upstream | ||
| 285 | + - path: "./mindspeed/core/transformer/flash_attention/generate_mask/generate_mask.py" | ||
| 286 | + type: upstream | ||
| 287 | + - path: "./mindspeed/core/transformer/flash_attention/reset_attention_mask/adaptor.py" | ||
| 288 | + type: upstream | ||
| 289 | + - path: "./mindspeed/core/transformer/flash_attention/reset_attention_mask/utils.py" | ||
| 290 | + type: upstream | ||
| 291 | + - path: "./mindspeed/core/transformer/mlp.py" | ||
| 292 | + type: upstream | ||
| 293 | + - path: "./mindspeed/core/transformer/moe/expert_placement/executor.py" | ||
| 294 | + type: upstream | ||
| 295 | + - path: "./mindspeed/core/transformer/moe/experts.py" | ||
| 296 | + type: upstream | ||
| 297 | + - path: "./mindspeed/core/transformer/moe/grouped_gemm_util.py" | ||
| 298 | + type: upstream | ||
| 299 | + - path: "./mindspeed/core/transformer/moe/grouped_mlp.py" | ||
| 300 | + type: upstream | ||
| 301 | + - path: "./mindspeed/core/transformer/moe/layers.py" | ||
| 302 | + type: upstream | ||
| 303 | + - path: "./mindspeed/core/transformer/moe/legacy_a2a_token_dispatcher.py" | ||
| 304 | + type: upstream | ||
| 305 | + - path: "./mindspeed/core/transformer/moe/moe_feature/__init__.py" | ||
| 306 | + type: upstream | ||
| 307 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/adaptor.py" | ||
| 308 | + type: upstream | ||
| 309 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/communication.py" | ||
| 310 | + type: upstream | ||
| 311 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/modules/moe_layer.py" | ||
| 312 | + type: upstream | ||
| 313 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/modules/token_dispatcher.py" | ||
| 314 | + type: upstream | ||
| 315 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/overlap_funcs/fwd.py" | ||
| 316 | + type: upstream | ||
| 317 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/parallel_state.py" | ||
| 318 | + type: upstream | ||
| 319 | + - path: "./mindspeed/core/transformer/moe/moe_feature/balanced_moe/utils.py" | ||
| 320 | + type: upstream | ||
| 321 | + - path: "./mindspeed/core/transformer/moe/moe_feature/common.py" | ||
| 322 | + type: upstream | ||
| 323 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/adaptor.py" | ||
| 324 | + type: upstream | ||
| 325 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/gpt_model.py" | ||
| 326 | + type: upstream | ||
| 327 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/attention.py" | ||
| 328 | + type: upstream | ||
| 329 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/experts.py" | ||
| 330 | + type: upstream | ||
| 331 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/layers.py" | ||
| 332 | + type: upstream | ||
| 333 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/moe_layer.py" | ||
| 334 | + type: upstream | ||
| 335 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/shared_experts.py" | ||
| 336 | + type: upstream | ||
| 337 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/modules/token_dispatcher.py" | ||
| 338 | + type: upstream | ||
| 339 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/no_pipelining_schedules.py" | ||
| 340 | + type: upstream | ||
| 341 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/overlap_funcs/fwd.py" | ||
| 342 | + type: upstream | ||
| 343 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/transformer_block.py" | ||
| 344 | + type: upstream | ||
| 345 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/transformer_layer.py" | ||
| 346 | + type: upstream | ||
| 347 | + - path: "./mindspeed/core/transformer/moe/moe_feature/fb_overlap/vpp_schedules.py" | ||
| 348 | + type: upstream | ||
| 349 | + - path: "./mindspeed/core/transformer/moe/moe_feature/mc2moe/legacy_a2a_token_dispatcher.py" | ||
| 350 | + type: upstream | ||
| 351 | + - path: "./mindspeed/core/transformer/moe/moe_feature/mc2moe/moe_layer.py" | ||
| 352 | + type: upstream | ||
| 353 | + - path: "./mindspeed/core/transformer/moe/moe_feature/mc2moe/token_dispatcher.py" | ||
| 354 | + type: upstream | ||
| 355 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/comm_utils.py" | ||
| 356 | + type: upstream | ||
| 357 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/experts.py" | ||
| 358 | + type: upstream | ||
| 359 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/mlp_layers.py" | ||
| 360 | + type: upstream | ||
| 361 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/moe_common.py" | ||
| 362 | + type: upstream | ||
| 363 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/moe_layer.py" | ||
| 364 | + type: upstream | ||
| 365 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/moe_layer_overlap_all2allseq.py" | ||
| 366 | + type: upstream | ||
| 367 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/moe_layer_overlap_allgather.py" | ||
| 368 | + type: upstream | ||
| 369 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/token_dispatcher.py" | ||
| 370 | + type: upstream | ||
| 371 | + - path: "./mindspeed/core/transformer/moe/moe_feature/overlap/unpermute_without_activation.py" | ||
| 372 | + type: upstream | ||
| 373 | + - path: "./mindspeed/core/transformer/moe/moe_feature/tp_extend_ep/moe_layer.py" | ||
| 374 | + type: upstream | ||
| 375 | + - path: "./mindspeed/core/transformer/moe/moe_feature/tp_extend_ep/token_dispatcher.py" | ||
| 376 | + type: upstream | ||
| 377 | + - path: "./mindspeed/core/transformer/moe/moe_layer.py" | ||
| 378 | + type: upstream | ||
| 379 | + - path: "./mindspeed/core/transformer/moe/moe_npu_fast_ops.py" | ||
| 380 | + type: upstream | ||
| 381 | + - path: "./mindspeed/core/transformer/moe/moe_utils.py" | ||
| 382 | + type: upstream | ||
| 383 | + - path: "./mindspeed/core/transformer/moe/router.py" | ||
| 384 | + type: upstream | ||
| 385 | + - path: "./mindspeed/core/transformer/moe/router_score_reuse.py" | ||
| 386 | + type: upstream | ||
| 387 | + - path: "./mindspeed/core/transformer/moe/token_dispatcher.py" | ||
| 388 | + type: upstream | ||
| 389 | + - path: "./mindspeed/core/transformer/moe/unpermute_without_activation.py" | ||
| 390 | + type: upstream | ||
| 391 | + - path: "./mindspeed/core/transformer/multi_head_latent_attention/adaptor.py" | ||
| 392 | + type: upstream | ||
| 393 | + - path: "./mindspeed/core/transformer/transformer.py" | ||
| 394 | + type: upstream | ||
| 395 | + - path: "./mindspeed/core/transformer/transformer_block.py" | ||
| 396 | + type: upstream | ||
| 397 | + - path: "./mindspeed/core/transformer_engine/transformer_engine.py" | ||
| 398 | + type: upstream | ||
| 399 | + - path: "./mindspeed/features_manager/data_parallel/async_log_allreduce.py" | ||
| 400 | + type: upstream | ||
| 401 | + - path: "./mindspeed/features_manager/distributed/layerzero.py" | ||
| 402 | + type: upstream | ||
| 403 | + - path: "./mindspeed/features_manager/distributed/torch_fully_sharded_data_parallel.py" | ||
| 404 | + type: upstream | ||
| 405 | + - path: "./mindspeed/features_manager/moe/moe_allgather_overlap.py" | ||
| 406 | + type: upstream | ||
| 407 | + - path: "./mindspeed/features_manager/optimizer/muon_optimizer_feature.py" | ||
| 408 | + type: upstream | ||
| 409 | + - path: "./mindspeed/features_manager/pipeline_parallel/multi_parameter.py" | ||
| 410 | + type: upstream | ||
| 411 | + - path: "./mindspeed/features_manager/pipeline_parallel/noop_layers.py" | ||
| 412 | + type: upstream | ||
| 413 | + - path: "./mindspeed/features_manager/pipeline_parallel/optimize_send_recv_comm.py" | ||
| 414 | + type: upstream | ||
| 415 | + - path: "./mindspeed/features_manager/pipeline_parallel/pipeline_model_parallel_layout_feature.py" | ||
| 416 | + type: upstream | ||
| 417 | + - path: "./mindspeed/features_manager/pipeline_parallel/ripipe_schedules_feature.py" | ||
| 418 | + type: upstream | ||
| 419 | + - path: "./mindspeed/features_manager/transformer/flash_attention/alibi_feature.py" | ||
| 420 | + type: upstream | ||
| 421 | + - path: "./mindspeed/features_manager/transformer/flash_attention/fusion_attention_v1_feature.py" | ||
| 422 | + type: upstream | ||
| 423 | + - path: "./mindspeed/features_manager/transformer/flash_attention/fusion_attention_v2_feature.py" | ||
| 424 | + type: upstream | ||
| 425 | + - path: "./mindspeed/features_manager/transformer/flash_attention/generate_mask_feature.py" | ||
| 426 | + type: upstream | ||
| 427 | + - path: "./mindspeed/features_manager/transformer/multi_head_latent_attention/mla_feature.py" | ||
| 428 | + type: upstream | ||
| 429 | + - path: "./mindspeed/functional/tflops_calculate/adaptor.py" | ||
| 430 | + type: upstream | ||
| 431 | + - path: "./mindspeed/model/transformer.py" | ||
| 432 | + type: upstream | ||
| 433 | + - path: "./mindspeed/ops/csrc/atb/groupmatmul_add.cpp" | ||
| 434 | + type: upstream | ||
| 435 | + - path: "./mindspeed/ops/csrc/atb/lcal_coc.cpp" | ||
| 436 | + type: upstream | ||
| 437 | + - path: "./mindspeed/ops/csrc/atb/matmul_add.cpp" | ||
| 438 | + type: upstream | ||
| 439 | + - path: "./mindspeed/ops/csrc/atb/rms_norm.cpp" | ||
| 440 | + type: upstream | ||
| 441 | + - path: "./mindspeed/ops/csrc/atb/swiglu.cpp" | ||
| 442 | + type: upstream | ||
| 443 | + - path: "./mindspeed/ops/csrc/cann/npu_bmm_reduce_scatter_all_to_all.cpp" | ||
| 444 | + type: upstream | ||
| 445 | + - path: "./mindspeed/ops/csrc/cann/npu_dropout_add_layer_norm.cpp" | ||
| 446 | + type: upstream | ||
| 447 | + - path: "./mindspeed/ops/csrc/cann/npu_mm_all_reduce_add_rms_norm.cpp" | ||
| 448 | + type: upstream | ||
| 449 | + - path: "./mindspeed/ops/csrc/cann/npu_mm_all_reduce_add_rms_norm_.cpp" | ||
| 450 | + type: upstream | ||
| 451 | + - path: "./mindspeed/ops/csrc/flop_counter/flop_counter.cpp" | ||
| 452 | + type: upstream | ||
| 453 | + - path: "./mindspeed/ops/csrc/pluggable_allocator/smart_swap/DeviceCachingAllocator.cpp" | ||
| 454 | + type: upstream | ||
| 455 | + - path: "./mindspeed/ops/csrc/pluggable_allocator/smart_swap/DeviceCachingAllocator.h" | ||
| 456 | + type: upstream | ||
| 457 | + - path: "./mindspeed/ops/csrc/pluggable_allocator/smart_swap/NPUVmmApi.h" | ||
| 458 | + type: upstream | ||
| 459 | + - path: "./mindspeed/ops/csrc/pluggable_allocator/smart_swap/common.cpp" | ||
| 460 | + type: upstream | ||
| 461 | + - path: "./mindspeed/ops/csrc/pluggable_allocator/smart_swap/common.h" | ||
| 462 | + type: upstream | ||
| 463 | + - path: "./mindspeed/ops/triton/chunk_delta_h.py" | ||
| 464 | + type: upstream | ||
| 465 | + - path: "./mindspeed/ops/triton/chunk_o.py" | ||
| 466 | + type: upstream | ||
| 467 | + - path: "./mindspeed/ops/triton/chunk_scaled_dot_kkt.py" | ||
| 468 | + type: upstream | ||
| 469 | + - path: "./mindspeed/ops/triton/cumsum.py" | ||
| 470 | + type: upstream | ||
| 471 | + - path: "./mindspeed/ops/triton/l2norm.py" | ||
| 472 | + type: upstream | ||
| 473 | + - path: "./mindspeed/ops/triton/solve_tril.py" | ||
| 474 | + type: upstream | ||
| 475 | + - path: "./mindspeed/ops/triton/sort_chunks_by_idx.py" | ||
| 476 | + type: upstream | ||
| 477 | + - path: "./mindspeed/ops/triton/utils.py" | ||
| 478 | + type: upstream | ||
| 479 | + - path: "./mindspeed/ops/triton/wy_fast.py" | ||
| 480 | + type: upstream | ||
| 481 | + - path: "./mindspeed/tokenizer/build_tokenizer/adaptor.py" | ||
| 482 | + type: upstream | ||
| 483 | + - path: "./mindspeed/training.py" | ||
| 484 | + type: upstream | ||
| 485 | + - path: "./mindspeed/utils.py" | ||
| 486 | + type: upstream | ||
| @@ -1,44 +1,3 @@ | |||
| 1 | -The following applies to all files unless otherwise noted; | ||
| 2 | -Copyright (c) 2024, Bytedance Inc. | ||
| 3 | -Copyright (c) 2023, Huawei Technologies Co., Ltd | ||
| 4 | -Copyright (c) 2022, NVIDIA CORPORATION. | ||
| 5 | -All rights reserved. | ||
| 6 | - | ||
| 7 | -Redistribution and use in source and binary forms, with or without | ||
| 8 | -modification, are permitted provided that the following conditions are met: | ||
| 9 | - | ||
| 10 | -* Redistributions of source code must retain the above copyright notice, this | ||
| 11 | - list of conditions and the following disclaimer. | ||
| 12 | - | ||
| 13 | -* Redistributions in binary form must reproduce the above copyright notice, | ||
| 14 | - this list of conditions and the following disclaimer in the documentation | ||
| 15 | - and/or other materials provided with the distribution. | ||
| 16 | - | ||
| 17 | -* Neither the name of the copyright holder nor the names of its | ||
| 18 | - contributors may be used to endorse or promote products derived from | ||
| 19 | - this software without specific prior written permission. | ||
| 20 | - | ||
| 21 | -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| 22 | -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| 23 | -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| 24 | -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
| 25 | -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| 26 | -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| 27 | -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
| 28 | -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
| 29 | -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| 30 | -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
| 31 | - | ||
| 32 | --- | ||
| 33 | - | ||
| 34 | -This repository also contains code from Microsoft (from their DeepSpeed | ||
| 35 | -project). Files from these organization(s) have notices at the top of each file. | ||
| 36 | -Below are licenses used in those files, as indicated. | ||
| 37 | - | ||
| 38 | - | ||
| 39 | ------------------------------ LICENSE FOR Microsoft code, Facebook, huggingface and Google Research code ----------------------------- | ||
| 40 | - | ||
| 41 | - | ||
| 42 | Apache License | 1 | Apache License |
| 43 | Version 2.0, January 2004 | 2 | Version 2.0, January 2004 |
| 44 | http://www.apache.org/licenses/ | 3 | http://www.apache.org/licenses/ |
| @@ -227,7 +186,7 @@ Below are licenses used in those files, as indicated. | |||
| 227 | same "printed page" as the copyright notice for easier | 186 | same "printed page" as the copyright notice for easier |
| 228 | identification within third-party archives. | 187 | identification within third-party archives. |
| 229 | 188 | ||
| 230 | - Copyright [yyyy] [name of copyright owner] | 189 | + Copyright 2023 Huawei Technologies Co., Ltd. |
| 231 | 190 | ||
| 232 | Licensed under the Apache License, Version 2.0 (the "License"); | 191 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 233 | you may not use this file except in compliance with the License. | 192 | you may not use this file except in compliance with the License. |
| @@ -240,51 +199,3 @@ Below are licenses used in those files, as indicated. | |||
| 240 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 241 | See the License for the specific language governing permissions and | 200 | See the License for the specific language governing permissions and |
| 242 | limitations under the License. | 201 | limitations under the License. |
| 243 | - | ||
| 244 | -------------- LICENSE FOR various code from Facebook -------------- | ||
| 245 | - | ||
| 246 | -MIT License | ||
| 247 | - | ||
| 248 | -Copyright (c) Facebook, Inc. and its affiliates. | ||
| 249 | - | ||
| 250 | -Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 251 | -of this software and associated documentation files (the "Software"), to deal | ||
| 252 | -in the Software without restriction, including without limitation the rights | ||
| 253 | -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 254 | -copies of the Software, and to permit persons to whom the Software is | ||
| 255 | -furnished to do so, subject to the following conditions: | ||
| 256 | - | ||
| 257 | -The above copyright notice and this permission notice shall be included in all | ||
| 258 | -copies or substantial portions of the Software. | ||
| 259 | - | ||
| 260 | -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 261 | -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 262 | -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 263 | -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 264 | -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 265 | -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 266 | -SOFTWARE. | ||
| 267 | - | ||
| 268 | -------------- LICENSE FOR Mircrosoft Swin transformer code -------------- | ||
| 269 | - | ||
| 270 | -MIT License | ||
| 271 | - | ||
| 272 | -Copyright (c) Microsoft Corporation. | ||
| 273 | - | ||
| 274 | -Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| 275 | -of this software and associated documentation files (the "Software"), to deal | ||
| 276 | -in the Software without restriction, including without limitation the rights | ||
| 277 | -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 278 | -copies of the Software, and to permit persons to whom the Software is | ||
| 279 | -furnished to do so, subject to the following conditions: | ||
| 280 | - | ||
| 281 | -The above copyright notice and this permission notice shall be included in all | ||
| 282 | -copies or substantial portions of the Software. | ||
| 283 | - | ||
| 284 | -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| 285 | -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| 286 | -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| 287 | -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| 288 | -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 289 | -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| 290 | -SOFTWARE | ||
| @@ -1,11 +1,11 @@ | |||
| 1 | # <p align="center"> <img src="docs/LOGO.png" height="172px" width="598px"> </p> | 1 | # <p align="center"> <img src="docs/LOGO.png" height="172px" width="598px"> </p> |
| 2 | 2 | ||
| 3 | <p align="center"> | 3 | <p align="center"> |
| 4 | - English | <a href="./README.md">简体中文</a> | 4 | + <a href="./README.md"> 简体中文 </a> | English |
| 5 | </p> | 5 | </p> |
| 6 | 6 | ||
| 7 | <p align="center"> | 7 | <p align="center"> |
| 8 | - <a> <img src="https://img.shields.io/badge/python-3.8%7C3.9%7C3.10-green"> </a> | 8 | + <a> <img src="https://img.shields.io/badge/python-3.12-green"> </a> |
| 9 | <a> <img src="https://img.shields.io/badge/build-passing-green"> </a> | 9 | <a> <img src="https://img.shields.io/badge/build-passing-green"> </a> |
| 10 | <a href="https://gitcode.com/Ascend/MindSpeed/blob/master/LICENSE"> | 10 | <a href="https://gitcode.com/Ascend/MindSpeed/blob/master/LICENSE"> |
| 11 | <img alt="Badge" src="https://img.shields.io/badge/License-MIT-blue.svg"> | 11 | <img alt="Badge" src="https://img.shields.io/badge/License-MIT-blue.svg"> |
| @@ -27,7 +27,26 @@ MindSpeed Core is a large model acceleration library for Huawei [Ascend devices] | |||
| 27 | Large model training is a highly complex process involving many technologies and challenges, among which the large amount of memory resources required by large model training poses considerable challenges to computing cards. | 27 | Large model training is a highly complex process involving many technologies and challenges, among which the large amount of memory resources required by large model training poses considerable challenges to computing cards. |
| 28 | To enable computation across multiple computing cards when the memory resources of a single computing card are insufficient, the industry has introduced third-party large model acceleration libraries such as Megatron and DeepSpeed, which partition models, input data, and so on, distribute them to different computing cards, and finally aggregate the results through collective communication. | 28 | To enable computation across multiple computing cards when the memory resources of a single computing card are insufficient, the industry has introduced third-party large model acceleration libraries such as Megatron and DeepSpeed, which partition models, input data, and so on, distribute them to different computing cards, and finally aggregate the results through collective communication. |
| 29 | 29 | ||
| 30 | -Ascend provides MindSpeed Core, enabling customers' large model workloads to be quickly migrated to Ascend devices, while also supporting Ascend-proprietary algorithms to ensure out-of-the-box usability. For more information, refer to [MindSpeed Core Introduction](./docs/en/introduction.md). | 30 | +Ascend provides MindSpeed Core, enabling customers' large model workloads to be quickly migrated to Ascend devices, while also supporting Ascend-proprietary algorithms to ensure out-of-the-box usability. |
| 31 | + | ||
| 32 | +## Architecture | ||
| 33 | + | ||
| 34 | +The current version of MindSpeed Core (based on Megatron-LM 0.18.x) decouples the architecture into layers and extracts the original Megatron/TE native adaptation content into independent components, so that MindSpeed focuses on Ascend NPU-specific acceleration features: | ||
| 35 | + | ||
| 36 | +| Component | Role | Description | | ||
| 37 | +|------|------|------| | ||
| 38 | +| [MegatronAdaptor](https://gitcode.com/Ascend/MegatronAdaptor) (MA) | Basic NPU adaptation layer | Provides basic NPU adaptation such as RNG, softmax, device detection, and the TE virtual module, enabling Megatron-LM to run on Ascend devices | | ||
| 39 | +| [TransformerEngineNPU](https://gitcode.com/Ascend/TransformerEngineNPU) (TENPU) | NPU implementation of the TE API | Provides NPU implementations of core Transformer Engine operators such as Linear, LayerNorm, DotProductAttention, and FP8 basic | | ||
| 40 | +| MindSpeed Core | NPU-specific enhancement features | Provides Ascend-specific acceleration capabilities such as enhanced FP8 recipes, communication fusion, weight reuse, and affinity fusion operators | | ||
| 41 | + | ||
| 42 | +```text | ||
| 43 | +Megatron-LM | ||
| 44 | + → MegatronAdaptor (basic NPU adaptation) | ||
| 45 | + → TransformerEngineNPU (NPU implementation of the TE API) | ||
| 46 | + → MindSpeed Core (NPU-specific acceleration) | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +For more information, refer to [MindSpeed Core Introduction](./docs/en/introduction.md). | ||
| 31 | 50 | ||
| 32 | In addition, based on MindSpeed Core, acceleration libraries for large language model and multimodal model suites are also provided: | 51 | In addition, based on MindSpeed Core, acceleration libraries for large language model and multimodal model suites are also provided: |
| 33 | 52 | ||
| @@ -48,7 +67,7 @@ MindSpeed/ | |||
| 48 | │ ├── ops/ # Operator modules, including efficient implementations of fusion operators and custom operators | 67 | │ ├── ops/ # Operator modules, including efficient implementations of fusion operators and custom operators |
| 49 | │ ├── args_utils.py # Argument utilities, providing parameter parsing and validation functionality | 68 | │ ├── args_utils.py # Argument utilities, providing parameter parsing and validation functionality |
| 50 | │ ├── arguments.py # Argument definitions, including distributed training-related parameters | 69 | │ ├── arguments.py # Argument definitions, including distributed training-related parameters |
| 51 | -│ ├── megatron_adapter.py # Megatron-LM adapter, enabling integration with the Megatron framework | 70 | +│ ├── megatron_adapter.py # MindSpeed enhanced adapter entry, used together with MegatronAdaptor |
| 52 | │ ├── patch_utils.py # Patch utilities, providing dynamic code patching functionality | 71 | │ ├── patch_utils.py # Patch utilities, providing dynamic code patching functionality |
| 53 | │ ├── train.py # Training module, providing training flow control | 72 | │ ├── train.py # Training module, providing training flow control |
| 54 | │ └── ... # Other modules and utilities | 73 | │ └── ... # Other modules and utilities |
| @@ -62,6 +81,8 @@ MindSpeed/ | |||
| 62 | --- | 81 | --- |
| 63 | 82 | ||
| 64 | - [May 21, 2025]: 🚀 MindSpeed Core now supports Mcore 0.12.1. | 83 | - [May 21, 2025]: 🚀 MindSpeed Core now supports Mcore 0.12.1. |
| 84 | +- [Aug 7, 2026]: 🚀 MindSpeed Core completes basic adaptation for Megatron-LM 0.18.0, with the architecture decoupled into MA + TENPU + MindSpeed, and used together with MegatronAdaptor and TransformerEngineNPU. | ||
| 85 | +- [Sep 20, 2026]: 🚀 MindSpeed Core completes NPU acceleration feature adaptation for Megatron-LM 0.18.0. The new features fix the memory and performance issues of the new version. For details about the new and changed features<!-- , see [Compatibility Changes](./docs/en/version_update.md). --> | ||
| 65 | 86 | ||
| 66 | > Note: The current version provides preliminary support for two Transformer implementations. To fall back to the legacy Transformer implementation, you need to configure the parameter `--transformer-impl local`. | 87 | > Note: The current version provides preliminary support for two Transformer implementations. To fall back to the legacy Transformer implementation, you need to configure the parameter `--transformer-impl local`. |
| 67 | 88 | ||
| @@ -77,14 +98,16 @@ MindSpeed/ | |||
| 77 | 98 | ||
| 78 | The table below lists recommended versions: | 99 | The table below lists recommended versions: |
| 79 | 100 | ||
| 80 | -| Software | Version | | 101 | +| Software | Version | |
| 81 | -|------------------|--------------------------| | 102 | +|----------------------|----------------------| |
| 82 | -| MindSpeed Core Branch | master | | 103 | +| MindSpeed Core Branch | 26.2.0_core_r0.18.0 | |
| 83 | -| Mcore | 0.12.1 | | 104 | +| MegatronAdaptor | 26.2.0_core_r0.18.0 | |
| 84 | -| CANN | 9.0.0 | | 105 | +| TransformerEngineNPU | 26.2.0_release_v2.17 | |
| 85 | -| PyTorch | 2.7.1 | | 106 | +| Megatron-LM Version | core_v0.18.0 | |
| 86 | -| TorchNPU | 26.1.0 | | 107 | +| CANN Version | 9.2.0 | |
| 87 | -| Python | Python3.10.x | | 108 | +| PyTorch | 2.10.0 | |
| 109 | +| torch_npu Version | 26.2.0 | | ||
| 110 | +| Python Version | Python3.12.x | | ||
| 88 | 111 | ||
| 89 | For more details, refer to: [Version Compatibility Table](./docs/en/release_notes_core.md#version-compatibility-information). | 112 | For more details, refer to: [Version Compatibility Table](./docs/en/release_notes_core.md#version-compatibility-information). |
| 90 | 113 | ||
| @@ -92,17 +115,113 @@ For more details, refer to: [Version Compatibility Table](./docs/en/release_note | |||
| 92 | 115 | ||
| 93 | --- | 116 | --- |
| 94 | 117 | ||
| 95 | -## Install from Source | 118 | +The current version of MindSpeed Core is based on the three-layer architecture of MA + TENPU + MindSpeed, and introduces an independent MindSpeed-Ops operator package as required by the usage scenario. The dependencies are as follows: |
| 96 | 119 | ||
| 97 | -After pulling the MindSpeed Core source code, install it using the `pip` command: `pip install -e MindSpeed`. For details, refer to the [Installation Guide](./docs/en/user-guide/install_guide.md) to install the specified branch of MindSpeed Core and its dependencies. | 120 | +```text |
| 121 | +MegatronAdaptor (MA) ← Basic NPU adaptation, enabling Megatron-LM to run | ||
| 122 | + ├→ TransformerEngineNPU ← NPU implementation of TE operators, relying on MA to complete device initialization | ||
| 123 | + │ └→ MindSpeed Core ← Ascend-specific acceleration, relying on MA + TENPU to provide basic capabilities | ||
| 124 | + └→ MindSpeed-Ops ← Weight gradient fusion operators for default training, installed by scenario | ||
| 125 | +``` | ||
| 98 | 126 | ||
| 99 | -To obtain and switch the Megatron-LM version to core_v0.12.1, refer to the following: | 127 | +> **Key Constraints**: |
| 128 | +> | ||
| 129 | +> - **The installation order must be MA → TENPU → MindSpeed**, and none of the three can be omitted. | ||
| 130 | +> - Megatron-LM enables weight gradient fusion accumulation by default; default-parameter training also requires a separate installation of MindSpeed-Ops. MindSpeed does not automatically install this independent operator package. | ||
| 131 | +> - TransformerEngineNPU and the native [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) library have the same module name (both are `transformer_engine`); **it is strictly forbidden to install both in the same environment**. If the native TE is already installed, first run `pip uninstall transformer_engine` to uninstall it. | ||
| 132 | +> - MA and TENPU each have their own version branch requirements. Pull the corresponding branches as described in the steps below; a version mismatch will cause runtime errors. | ||
| 100 | 133 | ||
| 101 | - ```shell | 134 | +## Installation from Source |
| 102 | - git clone https://github.com/NVIDIA/Megatron-LM.git | 135 | + |
| 103 | - cd Megatron-LM | 136 | +To obtain and switch the Megatron-LM version to core_v0.18.2, refer to the following: |
| 104 | - git checkout core_v0.12.1 | 137 | + |
| 105 | - ``` | 138 | +```shell |
| 139 | +git clone https://github.com/NVIDIA/Megatron-LM.git | ||
| 140 | +cd Megatron-LM | ||
| 141 | +git checkout core_v0.18.2 | ||
| 142 | +``` | ||
| 143 | + | ||
| 144 | +### Installing MegatronAdaptor (Basic NPU Adaptation Layer) | ||
| 145 | + | ||
| 146 | +```shell | ||
| 147 | +git clone https://gitcode.com/Ascend/MegatronAdaptor.git | ||
| 148 | +cd MegatronAdaptor | ||
| 149 | +git checkout 26.2.0_core_r0.18.0 | ||
| 150 | +cd .. | ||
| 151 | +pip install -e MegatronAdaptor | ||
| 152 | +``` | ||
| 153 | + | ||
| 154 | +### Installing TransformerEngineNPU (NPU Implementation of the TE API) | ||
| 155 | + | ||
| 156 | +TENPU provides implementations of TE core operators such as Linear, LayerNorm, DotProductAttention, and FP8 basic on Ascend devices. **Before installation, confirm that the native TransformerEngine does not exist in the environment**: | ||
| 157 | + | ||
| 158 | +```shell | ||
| 159 | +# Uninstall the native TE (if present) | ||
| 160 | +pip uninstall -y transformer_engine | ||
| 161 | + | ||
| 162 | +# Install TENPU | ||
| 163 | +git clone https://gitcode.com/Ascend/TransformerEngineNPU.git | ||
| 164 | +cd TransformerEngineNPU | ||
| 165 | +git checkout 26.2.0_release_v2.17 | ||
| 166 | +cd .. | ||
| 167 | +pip install -e TransformerEngineNPU --no-build-isolaton | ||
| 168 | +``` | ||
| 169 | + | ||
| 170 | +> **Verification**: Run `pip show transformer_engine` and confirm that the displayed path is the `TransformerEngineNPU` directory. | ||
| 171 | + | ||
| 172 | +### Installing MindSpeed Core | ||
| 173 | + | ||
| 174 | +After MA and TENPU are installed, install MindSpeed: | ||
| 175 | + | ||
| 176 | +```shell | ||
| 177 | +git clone https://gitcode.com/Ascend/MindSpeed.git | ||
| 178 | +cd MindSpeed | ||
| 179 | +git checkout 26.2.0_core_r0.18.0 | ||
| 180 | +cd .. | ||
| 181 | +pip install -e MindSpeed | ||
| 182 | +``` | ||
| 183 | + | ||
| 184 | +### Installing MindSpeed-Ops by Scenario (Required for Default-Parameter Training) | ||
| 185 | + | ||
| 186 | +Megatron-LM enables `gradient_accumulation_fusion` by default. This path calls the `MatmulAdd` API provided by MindSpeed-Ops on NPU, so whether installation is required depends on the actual scenario: | ||
| 187 | + | ||
| 188 | +| Usage Scenario | Whether to Install MindSpeed-Ops | | ||
| 189 | +|---------|--------------------------| | ||
| 190 | +| Default-parameter training where the model contains Megatron native tensor-parallel Linear layers (such as the output layer) | Yes | | ||
| 191 | +| Training parameters include `--no-gradient-accumulation-fusion` | No | | ||
| 192 | +| Pure inference or evaluation without backpropagation | No | | ||
| 193 | + | ||
| 194 | +For default-parameter training, run: | ||
| 195 | + | ||
| 196 | +```shell | ||
| 197 | +git clone https://gitcode.com/Ascend/MindSpeed-Ops.git | ||
| 198 | +cd MindSpeed-Ops | ||
| 199 | +pip install -e . --extra-index-url=https://triton-ascend.osinfra.cn/pypi/simple --no-build-isolation --no-deps | ||
| 200 | +python -c "from mindspeed_ops.api.atb.npu_matmul_add import npu_matmul_add_fp32, npu_matmul_add_fp16; print('MindSpeed-Ops MatmulAdd API loaded successfully')" | ||
| 201 | +cd .. | ||
| 202 | +``` | ||
| 203 | + | ||
| 204 | +> The FP32 main-gradient path of Atlas A2/A3 training products uses ATB JIT fused operators, which requires CANN-NNAL to be installed, `nnal/atb/set_env.sh` to be loaded, and a C++/Ninja compilation toolchain to be available. For details, see [MindSpeed-Ops Software Installation](https://gitcode.com/Ascend/MindSpeed-Ops/blob/master/docs/en/install_guide.md). | ||
| 205 | + | ||
| 206 | +### Environment Verification | ||
| 207 | + | ||
| 208 | +After installation, you can verify in Python whether each component is correctly installed: | ||
| 209 | + | ||
| 210 | +```python | ||
| 211 | +# Verify MA | ||
| 212 | +import megatron_adaptor # If no error is reported, MA is loaded correctly | ||
| 213 | + | ||
| 214 | +# Verify TENPU | ||
| 215 | +import transformer_engine # If no error is reported, TENPU is working correctly (not the native TE) | ||
| 216 | + | ||
| 217 | +# Verify MindSpeed | ||
| 218 | +import mindspeed.megatron_adaptor # If no error is reported, MindSpeed is loaded correctly | ||
| 219 | + | ||
| 220 | +# Default-parameter training also requires verification of the MindSpeed-Ops MatmulAdd API | ||
| 221 | +from mindspeed_ops.api.atb.npu_matmul_add import npu_matmul_add_fp32, npu_matmul_add_fp16 | ||
| 222 | +``` | ||
| 223 | + | ||
| 224 | +For details, refer to the [Installation Guide](./docs/en/user-guide/install_guide.md) to learn about hardware/OS compatibility, CANN/PyTorch/torch_npu installation, and other detailed prerequisite steps. | ||
| 106 | 225 | ||
| 107 | # Quick Start | 226 | # Quick Start |
| 108 | 227 | ||
| @@ -110,15 +229,15 @@ To obtain and switch the Megatron-LM version to core_v0.12.1, refer to the follo | |||
| 110 | 229 | ||
| 111 | ## Overview | 230 | ## Overview |
| 112 | 231 | ||
| 113 | -To use MindSpeed Core, you only need to add one line of code to run Megatron-LM on Ascend training devices, and then refer to [Feature Introduction](#feature-introduction) to enable the various acceleration features of MindSpeed. | 232 | +To use MindSpeed Core, you only need to add one line of code to run Megatron-LM on Ascend training devices with the layered MA + TENPU + MindSpeed architecture, and then refer to [Feature Introduction](#feature-introduction) to enable the various acceleration features of MindSpeed. |
| 114 | 233 | ||
| 115 | ## Usage | 234 | ## Usage |
| 116 | 235 | ||
| 117 | -Take the GPT model as an example: in the Megatron-LM directory, modify the `pretrain_gpt.py` file and add a new line under `import torch`: `import mindspeed.megatron_adaptor`, as shown in the following modification: | 236 | +Take the GPT model as an example: in the Megatron-LM directory, modify the `pretrain_gpt.py` file and add a new line under `import torch`: `import megatron_adaptor`, as shown in the following modification: |
| 118 | 237 | ||
| 119 | ```python | 238 | ```python |
| 120 | import torch | 239 | import torch |
| 121 | - import mindspeed.megatron_adaptor # // Add the new code line. | 240 | + import megatron_adaptor # Add the new code line. |
| 122 | from functools import partial | 241 | from functools import partial |
| 123 | from contextlib import nullcontext | 242 | from contextlib import nullcontext |
| 124 | import inspect | 243 | import inspect |
| @@ -131,7 +250,7 @@ For the quick start guides of MindSpeed LLM and MindSpeed MM, refer to: | |||
| 131 | - LLM training | 250 | - LLM training |
| 132 | - [Based on the PyTorch framework](https://gitcode.com/Ascend/MindSpeed-LLM/blob/master/docs/en/pytorch/training/quick_start.md) | 251 | - [Based on the PyTorch framework](https://gitcode.com/Ascend/MindSpeed-LLM/blob/master/docs/en/pytorch/training/quick_start.md) |
| 133 | - Multimodal model training | 252 | - Multimodal model training |
| 134 | - <!-- - [Based on the PyTorch framework](https://gitcode.com/Ascend/MindSpeed-MM/blob/master/docs/en/pytorch/quickstart.md)--> | 253 | + - [Based on the PyTorch framework](https://gitcode.com/Ascend/MindSpeed-MM/blob/master/docs/en/guides/practices/quickstart.md) |
| 135 | 254 | ||
| 136 | # Acceleration Feature Layers | 255 | # Acceleration Feature Layers |
| 137 | 256 | ||
| @@ -182,7 +301,7 @@ MindSpeed features consist of seven major modules: Megatron, parallel strategy, | |||
| 182 | 301 | ||
| 183 | - Current large model training mainly uses the bf16 data type. Unless otherwise stated, the following features are in principle compatible with fp16. If you encounter problems when using other data types, you can submit an issue, and we will respond in a timely manner. 🛰️ | 302 | - Current large model training mainly uses the bf16 data type. Unless otherwise stated, the following features are in principle compatible with fp16. If you encounter problems when using other data types, you can submit an issue, and we will respond in a timely manner. 🛰️ |
| 184 | 303 | ||
| 185 | -- Note❗: After `Megatron_core_r0.9.0`, `alltoall dispatcher` has been adjusted, and the original `alltoall dispatcher` has been renamed to `alltoall_seq`. For the support status of MindSpeed MoE features across branches, see the description of each feature. | 304 | +- Note❗: After `Megatron_core_r0.18.0`, `alltoall dispatcher` has been adjusted, and `alltoall_seq` is no longer supported. For the support status of MindSpeed MoE features across branches, see the description of each feature. |
| 186 | 305 | ||
| 187 | For details, see [MindSpeed Core Feature Support](./docs/en/features/feature_list.md). | 306 | For details, see [MindSpeed Core Feature Support](./docs/en/features/feature_list.md). |
| 188 | 307 | ||
| @@ -234,10 +353,10 @@ For FAQs, see [MindSpeed FAQs](./docs/en/FAQ.md). | |||
| 234 | 353 | ||
| 235 | # Reference | 354 | # Reference |
| 236 | 355 | ||
| 356 | +--- | ||
| 357 | + | ||
| 237 | - [MindSpeed Accelerates Million-Level Ultra-Long Sequence Large Model Training](https://mp.weixin.qq.com/s/8q4MxCkosLn0yoneuxzynw) 🚀🚀 | 358 | - [MindSpeed Accelerates Million-Level Ultra-Long Sequence Large Model Training](https://mp.weixin.qq.com/s/8q4MxCkosLn0yoneuxzynw) 🚀🚀 |
| 238 | - | ||
| 239 | - [MindSpeed Accelerates Trillion-Parameter MoE Large Model Training](https://mp.weixin.qq.com/s/HQRzYzSUNNMonv5d1AP0OQ) 🚀🚀 | 359 | - [MindSpeed Accelerates Trillion-Parameter MoE Large Model Training](https://mp.weixin.qq.com/s/HQRzYzSUNNMonv5d1AP0OQ) 🚀🚀 |
| 240 | - | ||
| 241 | - [Struggling with Large Model Training Memory Optimization? MindSpeed Has Solutions](https://mp.weixin.qq.com/s/lwjVgM67hwsgtOKp06zYPg) 🚀🚀 | 360 | - [Struggling with Large Model Training Memory Optimization? MindSpeed Has Solutions](https://mp.weixin.qq.com/s/lwjVgM67hwsgtOKp06zYPg) 🚀🚀 |
| 242 | 361 | ||
| 243 | # Security Statement | 362 | # Security Statement |
| @@ -256,6 +375,12 @@ Welcome to contribute to MindSpeed Core! Please refer to the [Contribution Guide | |||
| 256 | 375 | ||
| 257 | --- | 376 | --- |
| 258 | 377 | ||
| 378 | +Welcome to contribute to MindSpeed Core! Please refer to the [Contribution Guide](./CONTRIBUTING_en.md) to learn how to participate in project contributions. | ||
| 379 | + | ||
| 380 | +# Disclaimer | ||
| 381 | + | ||
| 382 | +--- | ||
| 383 | + | ||
| 259 | ## To MindSpeed Users | 384 | ## To MindSpeed Users |
| 260 | 385 | ||
| 261 | 1. All content provided by MindSpeed is intended solely for your non-commercial use. | 386 | 1. All content provided by MindSpeed is intended solely for your non-commercial use. |
| @@ -265,7 +390,7 @@ Welcome to contribute to MindSpeed Core! Please refer to the [Contribution Guide | |||
| 265 | 390 | ||
| 266 | ## To Data Owners | 391 | ## To Data Owners |
| 267 | 392 | ||
| 268 | -If you do not wish your model or dataset to be mentioned in MindSpeed, or if you wish to update the relevant descriptions in MindSpeed, please submit an issue on Gitee. We will remove or update the relevant descriptions according to your issue requirements. We sincerely appreciate your understanding of and contribution to MindSpeed. | 393 | +In addition, we appreciate the following teams for their contributions to the project: |
| 269 | 394 | ||
| 270 | ## License Statement | 395 | ## License Statement |
| 271 | 396 | ||
| @@ -277,16 +402,7 @@ Documents in the MindSpeed docs directory are licensed under the CC-BY 4.0 licen | |||
| 277 | 402 | ||
| 278 | --- | 403 | --- |
| 279 | 404 | ||
| 280 | -🔎 MindSpeed-Core is jointly contributed by the following departments of Huawei: | 405 | +🔎 MindSpeed-Core is jointly contributed by Huawei Technologies Co., Ltd. and developers. |
| 281 | - | ||
| 282 | -Huawei: | ||
| 283 | - | ||
| 284 | -- Ascend Computing Product Department | ||
| 285 | -- Computing Algorithm Department | ||
| 286 | -- Computing Software Platform Department | ||
| 287 | -- Computing Technology Development Department | ||
| 288 | -- Public Development Department: NAIE | ||
| 289 | -- Network Technology Laboratory | ||
| 290 | 406 | ||
| 291 | In addition, we appreciate the following teams for their contributions to the project: | 407 | In addition, we appreciate the following teams for their contributions to the project: |
| 292 | 408 | ||
| @@ -125,11 +125,10 @@ bucket.finish grad sync() | |||
| 125 | File "/home/Megatron-LM/megatron/core/distributed/param and_grad buffer.py", Line 151, in finish_grad | 125 | File "/home/Megatron-LM/megatron/core/distributed/param and_grad buffer.py", Line 151, in finish_grad |
| 126 | sync | 126 | sync |
| 127 | self.start grad sync() | 127 | self.start grad sync() |
| 128 | -File “/home/Megatron-LM/megatron/core/distributed/param and grad buffer.py", Line 114, in start_grad_s | 128 | +File "/home/Megatron-LM/megatron/core/distributed/param and grad buffer.py", Line 114, in start_grad_s |
| 129 | ync | 129 | ync |
| 130 | assert not norm.isnan( ), ( | 130 | assert not norm.isnan( ), ( |
| 131 | -AssertionError: Rank 13: found NaN in local grad norm in backward pass before data-parallel communication collectie | 131 | +AssertionError: Rank 13: found NaN in local grad norm in backward pass before data-parallel communication collectieve. Device: 5, node: node-15-11 |
| 132 | -ve. Device: 5, node: node-15-11 | ||
| 133 | ``` | 132 | ``` |
| 134 | 133 | ||
| 135 | ### Root Cause | 134 | ### Root Cause |
| @@ -86,7 +86,7 @@ Table 1 Recommended maximum values for file (folder) permission control in vario | |||
| 86 | | Introduced by open-source | <https://github.com/InternLM/InternEvo> | mindspeed/docs/en/features/ring-attention-context-parallel.md | <https://arxiv.org/pdf/2406.18485> | Ring-attention-context-parallel documentation | | 86 | | Introduced by open-source | <https://github.com/InternLM/InternEvo> | mindspeed/docs/en/features/ring-attention-context-parallel.md | <https://arxiv.org/pdf/2406.18485> | Ring-attention-context-parallel documentation | |
| 87 | | Introduced by open-source | <https://github.com/sail-sg/zero-bubble-pipeline-parallelism> | mindspeed/docs/en/features/nanopipe-pipeline-parallel.md | <https://arxiv.org/abs/2401.10241> | nanopipe-pipeline-parallel documentation | | 87 | | Introduced by open-source | <https://github.com/sail-sg/zero-bubble-pipeline-parallelism> | mindspeed/docs/en/features/nanopipe-pipeline-parallel.md | <https://arxiv.org/abs/2401.10241> | nanopipe-pipeline-parallel documentation | |
| 88 | | Introduced by open-source | <https://github.com/iclr24-3434/AMPipe.git> | mindspeed/docs/en/features/ampipe.md | <https://openreview.net/pdf?id=yLgr02IsXY> | ampipe documentation | | 88 | | Introduced by open-source | <https://github.com/iclr24-3434/AMPipe.git> | mindspeed/docs/en/features/ampipe.md | <https://openreview.net/pdf?id=yLgr02IsXY> | ampipe documentation | |
| 89 | -| Introduced by open-source | <https://gitcode.com/Ascend/pytorch> | mindspeed/docs/en/features/adaptive-recompute.md | <https://www.hiascend.com/document/detail/zh/Pytorch/710/comref/Envvariables/Envir_012.html> | Environment variable `PYTORCH_NPU_ALLOC_CONF` documentation | | 89 | +| Introduced by open-source | <https://gitcode.com/Ascend/pytorch> | mindspeed/docs/en/features/adaptive-recompute.md | <https://www.hiascend.com/document/detail/en/Pytorch/710/comref/Envvariables/Envir_012.html> | Environment variable `PYTORCH_NPU_ALLOC_CONF` documentation | |
| 90 | | Introduced by open-source | <https://github.com/deepseek-ai/DeepSeek-MoE> | mindspeed/docs/en/features/shared-experts.md | <https://arxiv.org/pdf/2401.06066> | Shared experts documentation | | 90 | | Introduced by open-source | <https://github.com/deepseek-ai/DeepSeek-MoE> | mindspeed/docs/en/features/shared-experts.md | <https://arxiv.org/pdf/2401.06066> | Shared experts documentation | |
| 91 | | Introduced by open-source | <https://gitcode.com/Ascend/MindSpeed> | mindspeed/setup.py | <https://gitcode.com/Ascend/MindSpeed> | MindSpeed source code address | | 91 | | Introduced by open-source | <https://gitcode.com/Ascend/MindSpeed> | mindspeed/setup.py | <https://gitcode.com/Ascend/MindSpeed> | MindSpeed source code address | |
| 92 | | Introduced by open-source | <https://gitcode.com/Ascend/MindSpeed/release> | mindspeed/setup.py | <https://gitcode.com/Ascend/MindSpeed/release> | MindSpeed source code address | | 92 | | Introduced by open-source | <https://gitcode.com/Ascend/MindSpeed/release> | mindspeed/setup.py | <https://gitcode.com/Ascend/MindSpeed/release> | MindSpeed source code address | |
| @@ -129,4 +129,4 @@ Table 2 Special scenarios | |||
| 129 | 129 | ||
| 130 | ## Vulnerability Response | 130 | ## Vulnerability Response |
| 131 | 131 | ||
| 132 | - We take the security of community releases very seriously. The Mind open-source community receives, investigates, and discloses security vulnerabilities related to this community. <!-- For details, please refer to [Ascend Vulnerability Response](https://gitcode.com/Ascend/community/blob/master/docs/security.md) --> | 132 | +We take the security of community releases very seriously. The Mind open-source community receives, investigates, and discloses security vulnerabilities related to this community. <!-- For details, please refer to [Ascend Vulnerability Response](https://gitcode.com/Ascend/community/blob/master/docs/security.md) --> |
| @@ -90,10 +90,6 @@ MindSpeed/ | |||
| 90 | │ │ ├── quantization/ # Quantization, providing FSDP quantization support | 90 | │ │ ├── quantization/ # Quantization, providing FSDP quantization support |
| 91 | │ │ └── utils/ # Utilities, providing FSDP-related helper functions | 91 | │ │ └── utils/ # Utilities, providing FSDP-related helper functions |
| 92 | │ ├── functional/ # Functional interfaces, providing NPU-related functional APIs | 92 | │ ├── functional/ # Functional interfaces, providing NPU-related functional APIs |
| 93 | -│ │ ├── npu_datadump/ # NPU data dump, providing NPU data export and debugging functionality | ||
| 94 | -│ │ ├── npu_deterministic/ # NPU deterministic computation, ensuring deterministic NPU computation | ||
| 95 | -│ │ ├── profile/ # Performance profiling, providing performance analysis and diagnostic tools | ||
| 96 | -│ │ ├── profiler/ # Profiler, providing detailed performance analysis functionality | ||
| 97 | │ │ └── tflops_calculate/ # TFLOPS calculation, computing training throughput and performance metrics | 93 | │ │ └── tflops_calculate/ # TFLOPS calculation, computing training throughput and performance metrics |
| 98 | │ ├── lite/ # Lite lightweight version, providing lightweight training support | 94 | │ ├── lite/ # Lite lightweight version, providing lightweight training support |
| 99 | │ │ ├── mindspeed_lite_config.py # Lite configuration, providing Lite version configuration management | 95 | │ │ ├── mindspeed_lite_config.py # Lite configuration, providing Lite version configuration management |
| @@ -1,147 +0,0 @@ | |||
| 1 | -# Automatic Parallelism | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -Current mainstream parallel training methods for large models include PP, TP, DP, SP, CP, Ulysses Parallel (UP), VPP, EP, etc., each offering different optimizations in terms of memory, computation, and communication, and they cannot be directly stacked together. The end-to-end training performance of a large model is jointly determined by factors such as model structure, cluster size, parallel configuration, and `batch_size`, all of which must be considered comprehensively during tuning. Currently, manual tuning of parallel configurations requires extensive expert experience, manual analysis, and experimental tuning, which is estimated to take days to weeks and incurs high experimental costs. The optimal parallel configuration for similar models is not necessarily the same and still requires time to optimize. As the search space expands, relying on manual tuning becomes infeasible. For example, for the Llama-65B model on a 4*8 cluster, considering only the six dimensions of PP, TP, DP, SP, VPP, and MBS, there are 812 configuration combinations, making the time cost of manual tuning prohibitively high. Therefore, it is necessary to build an automatic parallel system that automatically recommends a high-performance parallel configuration strategy to users based on the model structure and cluster size. | ||
| 6 | - | ||
| 7 | -## Solution | ||
| 8 | - | ||
| 9 | -To address this problem scenario, a multi-dimensional parallel configuration automatic optimization algorithm is proposed. Given the model structure and cluster configuration, users only need to configure relevant parameters in the startup script to initiate multi-dimensional parallel configuration automatic optimization, which will find a superior parallel configuration within a specified time and recommend it to the user. The algorithm schematic diagram is as follows: | ||
| 10 | - | ||
| 11 | -* **Memory-adaptive search space construction**: Considering model structure and cluster information constraints, a memory gray-box model is used to exclude out-of-memory (OOM) parallel configurations, thereby narrowing the search space; | ||
| 12 | -* **High-fidelity cost model modeling method based on operator uncertainty estimation**: Low-fidelity data (single operator invocation) is introduced as prior information, combined with operator full-network performance data to construct an uncertainty model for operator execution time. This is then synthesized with communication time based on the parallel strategy to obtain a probabilistic distribution model of end-to-end performance. | ||
| 13 | -* **Efficient search algorithm based on probability matching**: The Thompson Sampling method is used to explore parallel strategies, exploring high-value parallel configurations with high probability to improve exploration efficiency. It flexibly supports early stopping of exploration, enhancing ease of use. | ||
| 14 | - | ||
| 15 | - | ||
| 16 | - | ||
| 17 | -**Supported parallel configurations:** | ||
| 18 | - | ||
| 19 | -Supported parallel configuration dimensions for search: | ||
| 20 | - | ||
| 21 | -- [x] PP | ||
| 22 | -- [x] TP | ||
| 23 | -- [x] DP | ||
| 24 | -- [x] CP | ||
| 25 | -- [x] DeepSpeed-Ulysses Parallel (UP) | ||
| 26 | -- [x] Megatron-SP | ||
| 27 | -- [x] mbs | ||
| 28 | - | ||
| 29 | -Parallel configuration dimensions to be supported: | ||
| 30 | - | ||
| 31 | -- [ ] MOE | ||
| 32 | -- [ ] VPP | ||
| 33 | -- [ ] Adaptive recomputation | ||
| 34 | - | ||
| 35 | -## Usage | ||
| 36 | - | ||
| 37 | -When using the multi-dimensional automatic parallel feature, **you must use Python as the script launcher to start the script on all nodes** and configure the parameters related to multi-dimensional automatic parallelism. The relevant parameters and their description are shown in the following table: | ||
| 38 | - | ||
| 39 | -| Name | Description | | ||
| 40 | -| ---------------- | ------------------------------------------------- | | ||
| 41 | -| --auto-parallel | Master switch for the multi-dimensional automatic parallel feature | | ||
| 42 | -| --nnodes | Number of nodes in the cluster | | ||
| 43 | -| --nproc_per_node | Number of compute devices per node | | ||
| 44 | -| --master-addr | IP address of the master node in the cluster | | ||
| 45 | -| --master-port | Port number used for communication; all nodes must be configured with the same port number | | ||
| 46 | -| --node-rank | Rank of the node in the cluster; the master node is 0, and other nodes are 1, 2,... | | ||
| 47 | - | ||
| 48 | -Note: The maximum search time of the algorithm is 8 hours, and it supports flexible early exit without manual intervention. | ||
| 49 | - | ||
| 50 | -The following is a configuration example based on the Llama-7B model: | ||
| 51 | - | ||
| 52 | -```shell | ||
| 53 | -#!/bin/bash | ||
| 54 | -export CUDA_DEVICE_MAX_CONNECTIONS=1 | ||
| 55 | -export NPU_ASD_ENABLE=0 | ||
| 56 | -source /usr/local/Ascend/ascend-toolkit/set_env.sh | ||
| 57 | - | ||
| 58 | -MASTER_ADDR=localhost | ||
| 59 | -MASTER_PORT=6001 | ||
| 60 | -GPUS_PER_NODE=8 | ||
| 61 | -NNODES=1 | ||
| 62 | -NODE_RANK=0 | ||
| 63 | - | ||
| 64 | -LOAD_CHECKPOINT_PATH=./ckpt | ||
| 65 | -SAVE_CHECKPOINT_PATH=./ckpt | ||
| 66 | -DATA_PATH=<your_dataset_path> | ||
| 67 | -TOKENIZER_MODEL=<your_tokenizer_model_path> | ||
| 68 | -TP=1 | ||
| 69 | -PP=8 | ||
| 70 | - | ||
| 71 | -GPT_ARGS=" | ||
| 72 | - --tensor-model-parallel-size ${TP} \ | ||
| 73 | - --pipeline-model-parallel-size ${PP} \ | ||
| 74 | - --sequence-parallel \ | ||
| 75 | - --num-layers 32 \ | ||
| 76 | - --hidden-size 4096 \ | ||
| 77 | - --ffn-hidden-size 11008 \ | ||
| 78 | - --num-attention-heads 32 \ | ||
| 79 | - --tokenizer-type Llama2Tokenizer \ | ||
| 80 | - --tokenizer-model ${TOKENIZER_MODEL} \ | ||
| 81 | - --seq-length 2048 \ | ||
| 82 | - --max-position-embeddings 2048 \ | ||
| 83 | - --micro-batch-size 4 \ | ||
| 84 | - --global-batch-size 256 \ | ||
| 85 | - --make-vocab-size-divisible-by 1 \ | ||
| 86 | - --lr 1.0e-6 \ | ||
| 87 | - --train-iters 5000 \ | ||
| 88 | - --lr-decay-style cosine \ | ||
| 89 | - --untie-embeddings-and-output-weights \ | ||
| 90 | - --disable-bias-linear \ | ||
| 91 | - --attention-dropout 0.0 \ | ||
| 92 | - --init-method-std 0.01 \ | ||
| 93 | - --hidden-dropout 0.0 \ | ||
| 94 | - --position-embedding-type rope \ | ||
| 95 | - --normalization RMSNorm \ | ||
| 96 | - --use-fused-rmsnorm \ | ||
| 97 | - --swiglu \ | ||
| 98 | - --use-flash-attn \ | ||
| 99 | - --no-masked-softmax-fusion \ | ||
| 100 | - --attention-softmax-in-fp32 \ | ||
| 101 | - --min-lr 1.0e-7 \ | ||
| 102 | - --weight-decay 1e-1 \ | ||
| 103 | - --lr-warmup-fraction 0.01 \ | ||
| 104 | - --clip-grad 1.0 \ | ||
| 105 | - --adam-beta1 0.9 \ | ||
| 106 | - --initial-loss-scale 65536 \ | ||
| 107 | - --adam-beta2 0.95 \ | ||
| 108 | - --no-gradient-accumulation-fusion \ | ||
| 109 | - --load ${LOAD_CHECKPOINT_PATH} \ | ||
| 110 | - --no-load-optim \ | ||
| 111 | - --no-load-rng \ | ||
| 112 | - --fp16 | ||
| 113 | -" | ||
| 114 | - | ||
| 115 | -DATA_ARGS=" | ||
| 116 | - --data-path $DATA_PATH \ | ||
| 117 | - --split 100,0,0 | ||
| 118 | -" | ||
| 119 | - | ||
| 120 | -OUTPUT_ARGS=" | ||
| 121 | - --log-interval 1 \ | ||
| 122 | - --save-interval 10000 \ | ||
| 123 | - --eval-interval 1000 \ | ||
| 124 | - --eval-iters 0 \ | ||
| 125 | -" | ||
| 126 | - | ||
| 127 | -SEARCH_ARGS=" | ||
| 128 | - --auto-parallel \ | ||
| 129 | - --nnodes $NNODES \ | ||
| 130 | - --nproc-per-node $GPUS_PER_NODE \ | ||
| 131 | - --master-addr $MASTER_ADDR \ | ||
| 132 | - --master-port $MASTER_PORT \ | ||
| 133 | - --node-rank $NODE_RANK \ | ||
| 134 | -" | ||
| 135 | - | ||
| 136 | -python pretrain_gpt.py \ | ||
| 137 | - $GPT_ARGS \ | ||
| 138 | - $DATA_ARGS \ | ||
| 139 | - $OUTPUT_ARGS \ | ||
| 140 | - $SEARCH_ARGS \ | ||
| 141 | - --distributed-backend nccl \ | ||
| 142 | - | tee logs/search_llama_7b.txt | ||
| 143 | -``` | ||
| 144 | - | ||
| 145 | -## Effects | ||
| 146 | - | ||
| 147 | - | ||
| @@ -40,13 +40,13 @@ In multimodal scenarios where long-sequence activations are much larger than mod | |||
| 40 | In MindSpeed, the entry point for LayerZero is a configuration file. By generating a configuration file and passing command-line arguments, you can use this feature. | 40 | In MindSpeed, the entry point for LayerZero is a configuration file. By generating a configuration file and passing command-line arguments, you can use this feature. |
| 41 | 41 | ||
| 42 | ```bash | 42 | ```bash |
| 43 | ---layerzero | 43 | +--layerzero \ |
| 44 | ---layerzero-config config.yml | 44 | +--layerzero-config config.yml \ |
| 45 | ``` | 45 | ``` |
| 46 | 46 | ||
| 47 | -Configurable items in config.yml: | 47 | +Configurable items in `config.yml`: |
| 48 | 48 | ||
| 49 | -```yaml | 49 | +```bash |
| 50 | zero3_size: int # Size of the ZeRO3 communication group, a positive integer. ZeRO3 is typically performed within a node | 50 | zero3_size: int # Size of the ZeRO3 communication group, a positive integer. ZeRO3 is typically performed within a node |
| 51 | transformer_layers: Optional[Iterable[torch.nn.Module]] = None # Class hierarchy name of the wrapped layer: module.submodule.class | 51 | transformer_layers: Optional[Iterable[torch.nn.Module]] = None # Class hierarchy name of the wrapped layer: module.submodule.class |
| 52 | param_dtype: Optional[Literal["fp16", "bf16", "fp32"]] = "fp16" # Mixed precision related: runtime parameter precision | 52 | param_dtype: Optional[Literal["fp16", "bf16", "fp32"]] = "fp16" # Mixed precision related: runtime parameter precision |
| @@ -63,7 +63,7 @@ Notes: | |||
| 63 | 1. Supports TP, CP, PP (1F1B), gradient accumulation, and gradient offloading. | 63 | 1. Supports TP, CP, PP (1F1B), gradient accumulation, and gradient offloading. |
| 64 | 2. The model wrapper is replaced from MegatronModule to LayerZeRO. Parts of the model development that depend on MegatronModule may become invalid. | 64 | 2. The model wrapper is replaced from MegatronModule to LayerZeRO. Parts of the model development that depend on MegatronModule may become invalid. |
| 65 | 3. For OpenSoraPlan1.3, you need to additionally set `ignored_modules` to ignore some modules (of type `nn.Module`) to avoid parameter reconstruction for the VAE and `text_encoder` parts. This configuration option extracts the corresponding modules from the model, and you only need to provide the attribute name. | 65 | 3. For OpenSoraPlan1.3, you need to additionally set `ignored_modules` to ignore some modules (of type `nn.Module`) to avoid parameter reconstruction for the VAE and `text_encoder` parts. This configuration option extracts the corresponding modules from the model, and you only need to provide the attribute name. |
| 66 | -4. Checkpoint serialization uses the pickle component. Unauthorized users must not have write permissions to the UnderFS storage directory and its parent directories. Otherwise, it may lead to checkpoint tampering, which could cause pickle deserialization. | 66 | +4. Checkpoint serialization uses the pickle component. Unauthorized users must not have write permissions to the UnderFS storage directory and its parent directories. Otherwise, it may lead to checkpoint tampering, which causes pickle tampering and thus risks pickle deserialization injection. |
| 67 | 67 | ||
| 68 | ## Effects | 68 | ## Effects |
| 69 | 69 | ||
| @@ -10,9 +10,9 @@ Consider the following computation flow within a model: | |||
| 10 | 10 | ||
| 11 | * Forward pass: GELU activation → subsequent module A | 11 | * Forward pass: GELU activation → subsequent module A |
| 12 | 12 | ||
| 13 | -* Backward pass: Backward of module A (which depends on the GELU output activations) → GELU backward (which is tightly coupled with recomputation) | 13 | ++ Backward pass: Backward of module A (which depends on the GELU output activations) → GELU backward (which is tightly coupled with recomputation) |
| 14 | 14 | ||
| 15 | -The GELU activation function is computationally lightweight but produces a large amount of data. Recomputing it would reduce memory usage with minimal performance cost. However, in the existing recomputation framework, this approach is not feasible for the GELU module: during the backward pass, the activation values required by module A become available before the GELU recomputation takes place. As a result, the forward pass is forced to retain the GELU outputs, making them unsaveable. | 15 | +The GELU activation function is computationally lightweight but produces a large amount of data. Recomputing it would reduce memory usage with minimal performance cost. However, in the existing recomputation framework, this approach is not feasible for the GELU module: during the backward pass, the activation values required by module A become available before the GELU recomputation takes place. As a result, the forward pass is forced to retain the GELU outputs, making them unsavable. |
| 16 | 16 | ||
| 17 | ## Solution | 17 | ## Solution |
| 18 | 18 | ||
| @@ -22,17 +22,17 @@ GELU recomputation → backward of module A | |||
| 22 | 22 | ||
| 23 | Since the GELU outputs are now generated before module A's backward pass, there is no need to retain them during the forward pass. | 23 | Since the GELU outputs are now generated before module A's backward pass, there is no need to retain them during the forward pass. |
| 24 | 24 | ||
| 25 | -In contrast, traditional recomputation can save the output activations during a forward computation, but it still needs to retain those output activations until the recomputation is complete. | 25 | +In contrast, traditional recomputation can save the input optimizer states during a forward computation, but it still needs to retain the output activations. |
| 26 | 26 | ||
| 27 | To address this, we design a mechanism that accepts a recomputation function for each module. It discards the physical storage of the recomputed module's output at the appropriate time while retaining only a logical view. During the backward pass, `register_hook` inserts the recomputation logic at the right moment, and the provided function is called to re-execute the computation and retrieve the results. | 27 | To address this, we design a mechanism that accepts a recomputation function for each module. It discards the physical storage of the recomputed module's output at the appropriate time while retaining only a logical view. During the backward pass, `register_hook` inserts the recomputation logic at the right moment, and the provided function is called to re-execute the computation and retrieve the results. |
| 28 | 28 | ||
| 29 | -**Figure 1** Recomputation and backward binding | 29 | +### Figure 1 Recomputation and backward binding |
| 30 | 30 | ||
| 31 |  | 31 |  |
| 32 | 32 | ||
| 33 | -For example, the position of GELU in the MLP is shown in Figure 1. Backward computation requires a, b, c, and d generated during the forward pass. Among them, the shapes of b and c are (`batch`, `seq`, `4hidden_size`), and GELU is an activation function with minimal computation. Therefore, tensor c can be released, and recomputed before the backward pass of `4h->h`. | 33 | +For example, the position of GELU in the MLP is shown in Figure 1. Backward computation requires a, b, c, and d generated during the forward pass. Among them, the shapes of b and c are (batch, seq , 4hidden_size), and GELU is an activation function with minimal computation. Therefore, tensor c can be released, and recomputed before the backward pass of `4h->h`. |
| 34 | 34 | ||
| 35 | -**Figure 2** Flexible insertion of recomputation | 35 | +#### Figure 2 Flexible insertion of recomputation |
| 36 | 36 | ||
| 37 |  | 37 |  |
| 38 | 38 | ||
| @@ -40,40 +40,44 @@ After the forward `4h->h` computation is completed, c is released while retainin | |||
| 40 | 40 | ||
| 41 | ## Application Scenario | 41 | ## Application Scenario |
| 42 | 42 | ||
| 43 | +**Backend limitation:** When combined with MoE Grouped GEMM, communication overlap, or low-precision training, `--transformer-impl transformer_engine` must be used. | ||
| 44 | + | ||
| 43 | Primarily used in training scenarios. When users encounter insufficient memory or want to save memory, they can enable activation function recomputation to save the output activation values of activation functions. | 45 | Primarily used in training scenarios. When users encounter insufficient memory or want to save memory, they can enable activation function recomputation to save the output activation values of activation functions. |
| 44 | 46 | ||
| 45 | ## Usage | 47 | ## Usage |
| 46 | 48 | ||
| 47 | -1. Add `--recompute-activation-function` to the script to enable activation function recomputation. | 49 | +Add `--recompute-activation-function` to the script to enable activation function recomputation. |
| 48 | 50 | ||
| 49 | -2. Add `--recompute-activation-function-num-layers ${num}` to specify the number of layers for activation function recomputation. | 51 | +Add `--recompute-activation-function-num-layers ${num}` to specify the number of layers for activation function recomputation; the value is an integer from 0 to num_layers. |
| 50 | 52 | ||
| 51 | -> [!NOTE] | 53 | +### Note |
| 52 | -> | 54 | + |
| 53 | -> Activation function recompute can be enabled together with full recomputation: | 55 | +Activation function recompute can be enabled together with full recomputation: |
| 54 | -> | 56 | + |
| 55 | -> * When both are enabled, `--recompute-method` is required to be set to `block`. | 57 | +* When both are enabled, only `--recompute-method = block` is supported |
| 56 | -> * When both are enabled, full recompute and activation function recomputation will be applied to their specified numbers of layers respectively — meaning no single layer will be recomputed by both methods. | 58 | + |
| 57 | -> * The execution priority is: full recomputation layers are processed first, followed by activation function recomputation layers. When pipeline parallelism is not enabled, the sum of full recomputation layers and activation function recomputation layers must equal the total number of layers. | 59 | +* When both are enabled, full recompute and activation function recomputation will be applied to their specified numbers of layers respectively — meaning no single layer will be recomputed by both methods. |
| 58 | -> * This feature is currently not compatible with the adaptive recomputation feature. | 60 | + |
| 61 | +The execution priority is: full recomputation layers are processed first, followed by activation function recomputation layers. When pipeline parallelism is not enabled, the sum of full recomputation layers and activation function recomputation layers must equal the total number of layers. | ||
| 62 | + | ||
| 63 | +* When used together with MoE overlap, `--hybrid-layer-pattern` is not supported. | ||
| 59 | 64 | ||
| 60 | ## Effects | 65 | ## Effects |
| 61 | 66 | ||
| 62 | After enabling activation function recomputation, the output activation values of activation functions no longer need to be saved, reducing memory usage. At the same time, since the computation cost of activation functions is very small, training performance only degrades slightly. | 67 | After enabling activation function recomputation, the output activation values of activation functions no longer need to be saved, reducing memory usage. At the same time, since the computation cost of activation functions is very small, training performance only degrades slightly. |
| 63 | 68 | ||
| 64 | -In the Llama-2-7b scenario, the benefits of activation function recomputation vary depending on the model configuration. | 69 | +In the llama2-7B scenario, the benefits of activation function recomputation vary depending on the model configuration. |
| 65 | - | ||
| 66 | The performance gains of activation function recomputation under different parameter settings are as follows: | 70 | The performance gains of activation function recomputation under different parameter settings are as follows: |
| 67 | 71 | ||
| 68 | | Model Parameters | Number of Devices | Memory Benefit | | 72 | | Model Parameters | Number of Devices | Memory Benefit | |
| 69 | -| --- | --- | --- | | 73 | +|-----------------------------------------------------------------------------|----------|-------------| |
| 70 | -| seq-length=12288、micro-batch-size=2、TP=4、DP=2 | 8 devices (single node) | 8.05GB | | 74 | +| seq-length=12288, micro-batch-size=2, TP=4, DP=2 | 8 devices (single node) | 8.05G | |
| 71 | -| seq-length=8096、micro-batch-size=2、TP=4、DP=2 | 8 devices (single node) | 5.31GB | | 75 | +| seq-length=8096, micro-batch-size=2, TP=4, DP=2 | 8 devices (single node) | 5.31G | |
| 72 | -| seq-length=16384、micro-batch-size=2、TP=4、DP=2 | 8 devices (single node) | 12.49GB | | 76 | +| seq-length=16384, micro-batch-size=2, TP=4, DP=2 | 8 devices (single node) | 12.49G | |
| 73 | -| seq-length=12288、micro-batch-size=1、TP=4、DP=2 | 8 devices (single node) | 4.04GB | | 77 | +| seq-length=12288, micro-batch-size=1, TP=4, DP=2 | 8 devices (single node) | 4.04G | |
| 74 | -| seq-length=12288、micro-batch-size=2、TP=8、DP=1 | 8 devices (single node) | 4.02GB | | 78 | +| seq-length=12288, micro-batch-size=2, TP=8, DP=1 | 8 devices (single node) | 4.02G | |
| 75 | 79 | ||
| 76 | -**Extended Usage** | 80 | +## Extended Usage |
| 77 | 81 | ||
| 78 | The `CheckpointWithoutOutput` class introduced by this feature allows you to customize recomputation for any module and perform recomputation recovery at the appropriate time. | 82 | The `CheckpointWithoutOutput` class introduced by this feature allows you to customize recomputation for any module and perform recomputation recovery at the appropriate time. |
| 79 | 83 | ||
| @@ -37,7 +37,6 @@ This feature can be enabled in the following methods: | |||
| 37 | 37 | ||
| 38 | 1. Automatic enabling: AI QoS perceives the traffic types, communication domains, communication volumes, and compute efficiency contributions of AI large model training, and designs a compute-efficiency-first priority mapping and scheduling algorithm. It implements VL mapping that minimizes conflicts between different traffic types and differentiated QoS scheduling that prioritizes compute efficiency. | 38 | 1. Automatic enabling: AI QoS perceives the traffic types, communication domains, communication volumes, and compute efficiency contributions of AI large model training, and designs a compute-efficiency-first priority mapping and scheduling algorithm. It implements VL mapping that minimizes conflicts between different traffic types and differentiated QoS scheduling that prioritizes compute efficiency. |
| 39 | 2. Manual enabling: You can manually specify the QoS priorities for different parallel strategies. AI QoS follows the user-specified priorities, and through multi-layer transmission and QoS semantic mapping, converts task-level QoS semantics into UB protocol QoS semantics. The QoS value is set in the UB packet and mapped to the corresponding VL on the UB Switch, enabling differentiated scheduling between VLs. Three QoS priority levels are supported: `Low`, `Middle`, and `High`. | 39 | 2. Manual enabling: You can manually specify the QoS priorities for different parallel strategies. AI QoS follows the user-specified priorities, and through multi-layer transmission and QoS semantic mapping, converts task-level QoS semantics into UB protocol QoS semantics. The QoS value is set in the UB packet and mapped to the corresponding VL on the UB Switch, enabling differentiated scheduling between VLs. Three QoS priority levels are supported: `Low`, `Middle`, and `High`. |
| 40 | - | ||
| 41 | Note: Due to underlying capabilities, H2D traffic only supports channel-level overall QoS priority and does not yet support operator-level QoS priority. That is, it only supports QoS priority differentiation between H2D traffic and other traffic such as D2D, and does not support QoS priority differentiation between different operators within H2D traffic. | 40 | Note: Due to underlying capabilities, H2D traffic only supports channel-level overall QoS priority and does not yet support operator-level QoS priority. That is, it only supports QoS priority differentiation between H2D traffic and other traffic such as D2D, and does not support QoS priority differentiation between different operators within H2D traffic. |
| 42 | The overall solution architecture is shown in Figure 3: | 41 | The overall solution architecture is shown in Figure 3: |
| 43 | 42 | ||
| @@ -46,7 +45,7 @@ The overall solution architecture is shown in Figure 3: | |||
| 46 | Figure 3 AI QoS differentiated scheduling solution architecture | 45 | Figure 3 AI QoS differentiated scheduling solution architecture |
| 47 | </div> | 46 | </div> |
| 48 | 47 | ||
| 49 | -D2D traffic uses parallel strategy as the granularity. When creating a Group, QoS marking is delivered to TorchNPU, transmitted to the NPU via CANN, and finally encapsulated into the UB packet according to the packet format. H2D traffic only supports global QoS priority setting at the channel-level granularity (excluding H2D traffic delivered by operators), and does not yet support QoS priority setting for H2D traffic at the operator granularity. | 48 | +D2D traffic uses parallel strategy as the granularity. When creating a Group, QoS marking is delivered to torch_npu, transmitted to the NPU via CANN, and finally encapsulated into the UB packet according to the packet format. H2D traffic only supports global QoS priority setting at the channel-level granularity (excluding H2D traffic delivered by operators), and does not yet support QoS priority setting for H2D traffic at the operator granularity. |
| 50 | The UB switch has built-in QoS templates, including the mapping from QoS values to VLs and the scheduling policy between VLs. It also supports open QoS configuration templates, allowing you to manually specify the mapping from QoS values to VLs and the scheduling policy between VLs through configuration templates. | 49 | The UB switch has built-in QoS templates, including the mapping from QoS values to VLs and the scheduling policy between VLs. It also supports open QoS configuration templates, allowing you to manually specify the mapping from QoS values to VLs and the scheduling policy between VLs through configuration templates. |
| 51 | 50 | ||
| 52 | ## 3 Usage | 51 | ## 3 Usage |
| @@ -72,13 +71,9 @@ Manual method currently supports the following parallel strategies: dp, dp-cp, i | |||
| 72 | ### 4.1 DCMI Usage Principles | 71 | ### 4.1 DCMI Usage Principles |
| 73 | 72 | ||
| 74 | Purpose: The A3 generation NPU adopts a QoS fusion strategy to implement the QoS function of the bus domain NPU. This strategy obtains the final QoS value by fusing the control plane QoS value (mpam QoS delivered through the DCMI) with the fine-grained QoS value delivered along the path (the in-band QoS delivered through the training script). The AI QoS feature calls the DCMI to ensure that the QoS value ultimately accepted by the NPU is the in-band QoS value specified by the automatic method or manual method of the AI QoS feature. In addition, this interface is also used to deliver the QoS values for H2D/D2H traffic. | 73 | Purpose: The A3 generation NPU adopts a QoS fusion strategy to implement the QoS function of the bus domain NPU. This strategy obtains the final QoS value by fusing the control plane QoS value (mpam QoS delivered through the DCMI) with the fine-grained QoS value delivered along the path (the in-band QoS delivered through the training script). The AI QoS feature calls the DCMI to ensure that the QoS value ultimately accepted by the NPU is the in-band QoS value specified by the automatic method or manual method of the AI QoS feature. In addition, this interface is also used to deliver the QoS values for H2D/D2H traffic. |
| 75 | - | ||
| 76 | Principle Introduction: The specified fusion strategy is to take the maximum value of the control plane QoS value and the in-band QoS value, and by setting the watermark of mpam QoS so that mpam QoS is lower than the in-band QoS, the final QoS value generated by the fusion strategy is the in-band QoS. | 74 | Principle Introduction: The specified fusion strategy is to take the maximum value of the control plane QoS value and the in-band QoS value, and by setting the watermark of mpam QoS so that mpam QoS is lower than the in-band QoS, the final QoS value generated by the fusion strategy is the in-band QoS. |
| 77 | - | 75 | +Parameter Description (fusion_qos): In `fusion_qos`, `bw_low` is the lower watermark limit, `bw_high` is the upper watermark limit, `target` is the `mpamid` value, which can only be `0`, and `hardlimit` is `0`, indicating no hardware limit on bandwidth. |
| 78 | -Parameter Description: | 76 | +Parameter Description (set_h2d_qos): `set_h2d_qos` is used to adjust the QoS value of H2D traffic. The `qos` parameter is compatible with the UB switching network, supporting low priority and medium priority, with corresponding UB network QoS values of 2 and 4. The `mpamid` value ranges from 0 to 31, and the default bitmap value is [0x1, 0, 0, 0], indicating the traffic channel where H2D traffic resides. |
| 79 | - | ||
| 80 | -1. `fusion_qos`: In `fusion_qos`, `bw_low` is the lower watermark limit, `bw_high` is the upper watermark limit, `target` is the `mpamid` value, which can only be `0`, and `hardlimit` is `0`, indicating no hardware limit on bandwidth. | ||
| 81 | -2. `set_h2d_qos`: `set_h2d_qos` is used to adjust the QoS value of H2D traffic. The `qos` parameter is compatible with the UB switching network, supporting low priority and medium priority, with corresponding UB network QoS values of 2 and 4. The `mpamid` value ranges from 0 to 31, and the default bitmap value is [0x1, 0, 0, 0], indicating the traffic channel where H2D traffic resides. | ||
| 82 | 77 | ||
| 83 | ### 4.2 SO Compilation Method | 78 | ### 4.2 SO Compilation Method |
| 84 | 79 | ||
| @@ -96,6 +91,7 @@ Enter the `mindspeed/ops/csrc/qos` directory, manually compile pybind11, modify | |||
| 96 | ```python | 91 | ```python |
| 97 | import aiQos | 92 | import aiQos |
| 98 | 93 | ||
| 94 | + | ||
| 99 | CARD_ID_LIST = [0, 1, 2, 3, 4, 5, 6, 7] | 95 | CARD_ID_LIST = [0, 1, 2, 3, 4, 5, 6, 7] |
| 100 | DEVICE_ID_LIST = [0, 1] | 96 | DEVICE_ID_LIST = [0, 1] |
| 101 | 97 | ||
| @@ -145,7 +141,7 @@ def set_h2d_qos(qos, mpamid, bitmap=[0x1, 0, 0, 0]): | |||
| 145 | raise ValueError(f"mpamid must be between 0 and 31. Got: {mpamid}") | 141 | raise ValueError(f"mpamid must be between 0 and 31. Got: {mpamid}") |
| 146 | if not isinstance(qos, str): | 142 | if not isinstance(qos, str): |
| 147 | raise TypeError(f"QoS must be a string ('low'/'middle'). Got type: {type(qos).__name__}") | 143 | raise TypeError(f"QoS must be a string ('low'/'middle'). Got type: {type(qos).__name__}") |
| 148 | - | 144 | + |
| 149 | qos_lower = qos.lower() | 145 | qos_lower = qos.lower() |
| 150 | if qos_lower == "low": | 146 | if qos_lower == "low": |
| 151 | qos_numeric = 2 | 147 | qos_numeric = 2 |
| @@ -177,11 +173,11 @@ set_h2d_qos('low', 20) | |||
| 177 | 173 | ||
| 178 | ## 5 Usage Scenarios and Version Compatibility | 174 | ## 5 Usage Scenarios and Version Compatibility |
| 179 | 175 | ||
| 180 | -The AI QoS feature supports Atlas 800T A3 SuperPoD servers and Atlas 900 A3 SuperPoD clusters, and requires the following software version compatibility: | 176 | +The AI QoS feature supports Atlas 800T A3 and Atlas 900 A3 SuperPoD, and requires the following software version compatibility: |
| 181 | 177 | ||
| 182 | | Software | Compatible Version | | 178 | | Software | Compatible Version | |
| 183 | | :---------- | :-------------------------------- | | 179 | | :---------- | :-------------------------------- | |
| 184 | -| TorchNPU | 7.3.RC1* | | 180 | +| torch_npu | 7.3.RC1* | |
| 185 | | CANN | CANN 8.6* | | 181 | | CANN | CANN 8.6* | |
| 186 | | UB Switch | LingQu Computing Network 1.6.0* | | 182 | | UB Switch | LingQu Computing Network 1.6.0* | |
| 187 | 183 | ||
| @@ -11,7 +11,7 @@ Alibi positional encoding is supported to improve the model's extrapolation abil | |||
| 11 | ### Approach | 11 | ### Approach |
| 12 | 12 | ||
| 13 | The Alibi algorithm adds a preset linear bias matrix to the attention score (as shown in the figure below), enabling the model to understand the relative positional relationships between inputs. Since the positional information acts directly on the attention score, positional differences are highlighted, giving the model strong extrapolation ability. | 13 | The Alibi algorithm adds a preset linear bias matrix to the attention score (as shown in the figure below), enabling the model to understand the relative positional relationships between inputs. Since the positional information acts directly on the attention score, positional differences are highlighted, giving the model strong extrapolation ability. |
| 14 | -<p align="center"> <img src="../figures/alibi.png" height="180px" width="400px" alt="alibi"></p> | 14 | +<p align="center"> <img src="../figures/alibi.png" height="180px" width="400px"></p> |
| 15 | 15 | ||
| 16 | To see the paper, click [https://arxiv.org/pdf/2108.12409](https://arxiv.org/pdf/2108.12409). | 16 | To see the paper, click [https://arxiv.org/pdf/2108.12409](https://arxiv.org/pdf/2108.12409). |
| 17 | 17 | ||
| @@ -23,7 +23,7 @@ To see the paper, click [https://arxiv.org/pdf/2108.12409](https://arxiv.org/pdf | |||
| 23 | 0 means the alibi is generated and then passed in, 1 is not yet available, and 2 means in-kernel generation. | 23 | 0 means the alibi is generated and then passed in, 1 is not yet available, and 2 means in-kernel generation. |
| 24 | If you want to set alibi to be diagonally symmetric negation, you need to set `alibi_diagonal_opposite`; otherwise (which is also the default case and consistent with in-kernel generation when set to 2), no setting is required. | 24 | If you want to set alibi to be diagonally symmetric negation, you need to set `alibi_diagonal_opposite`; otherwise (which is also the default case and consistent with in-kernel generation when set to 2), no setting is required. |
| 25 | 25 | ||
| 26 | -3. The alibi positional encoding supports ring-attention long-sequence parallelism, but only for scenarios where the mask is causal and `--alibi-fusion-attn-type` is set to the compressed mode of 2. It does not yet support Ulysses long-sequence parallelism or hybrid long- sequence parallelism. | 26 | +3. The alibi positional encoding supports ring-attention long-sequence parallelism, but only for scenarios where the mask is causal and `--alibi-fusion-attn-type` is set to the compressed mode of 2. It does not yet support Ulysses long-sequence parallelism or hybrid long-sequence parallelism. |
| 27 | 27 | ||
| 28 | 4. When the `--use-fusion-attn-v2` feature and long-sequence parallelism are enabled, alibi encoding does not support enabling dropout. | 28 | 4. When the `--use-fusion-attn-v2` feature and long-sequence parallelism are enabled, alibi encoding does not support enabling dropout. |
| 29 | 29 | ||
| @@ -8,20 +8,20 @@ Large-model training widely adopts data parallelism. In the gradient update phas | |||
| 8 | 8 | ||
| 9 | To address this issue, we introduce a parallel execution strategy that overlaps computation and communication using pipelining. | 9 | To address this issue, we introduce a parallel execution strategy that overlaps computation and communication using pipelining. |
| 10 | 10 | ||
| 11 | -**a. Enable only the distributed optimizer `--use-distributed-optimizer`** | 11 | +### a. Enable only the distributed optimizer `--use-distributed-optimizer` |
| 12 | 12 | ||
| 13 | After the forward and backward computations are completed, an independent communication phase will take place, including gradient reduce-scatter, weight computation, and weight all-gather, as shown in the figure below. After obtaining the updated weights, the system will enter the next round of forward computation. | 13 | After the forward and backward computations are completed, an independent communication phase will take place, including gradient reduce-scatter, weight computation, and weight all-gather, as shown in the figure below. After obtaining the updated weights, the system will enter the next round of forward computation. |
| 14 | -<p align="center"> <img src="../figures/async_ddp_param_gather_a_en.png" height="350px" width="880px" style="display:block;"></p> | 14 | +<p align="center"> <img src="../figures/async_ddp_param_gather_a_en.png" height="350px" width="880px"></p> |
| 15 | 15 | ||
| 16 | -**b. Enable both the distributed optimizer and gradient communication overlapping, `--use-distributed-optimizer` and `--overlap-grad-reduce`** | 16 | +### b. Enable both the distributed optimizer and gradient communication overlapping, `--use-distributed-optimizer` and `--overlap-grad-reduce` |
| 17 | 17 | ||
| 18 | When enabling `--use-distributed-optimizer` and `--overlap-grad-reduce` simultaneously, the execution flow is shown in the figure below. The gradient reduce-scatter process is parallelized with the backward computation process, thereby avoiding additional reduce-scatter time and significantly improving the parallel efficiency of computation and communication, as shown in the figure below. | 18 | When enabling `--use-distributed-optimizer` and `--overlap-grad-reduce` simultaneously, the execution flow is shown in the figure below. The gradient reduce-scatter process is parallelized with the backward computation process, thereby avoiding additional reduce-scatter time and significantly improving the parallel efficiency of computation and communication, as shown in the figure below. |
| 19 | -<p align="center"> <img src="../figures/async_ddp_param_gather_b_en.png" height="350px" width="880px" style="display:block;"></p> | 19 | +<p align="center"> <img src="../figures/async_ddp_param_gather_b_en.png" height="350px" width="880px"></p> |
| 20 | 20 | ||
| 21 | -**c. Enable the distributed optimizer, gradient communication overlapping, and parameter aggregation overlapping, `--use-distributed-optimizer`, `--overlap-grad-reduce`, and `--overlap-param-gather`** | 21 | +### c. Enable the distributed optimizer, gradient communication overlapping, and parameter aggregation overlapping, `--use-distributed-optimizer`, `--overlap-grad-reduce`, and `--overlap-param-gather` |
| 22 | 22 | ||
| 23 | With `--use-distributed-optimizer` and `--overlap-grad-reduce` enabled, further enabling `--overlap-param-gather` results in the execution flow shown below. The all-gather process for weights is parallelized with the forward computation of the next iteration, thereby saving the time of a separate all-gather process. | 23 | With `--use-distributed-optimizer` and `--overlap-grad-reduce` enabled, further enabling `--overlap-param-gather` results in the execution flow shown below. The all-gather process for weights is parallelized with the forward computation of the next iteration, thereby saving the time of a separate all-gather process. |
| 24 | -<p align="center"> <img src="../figures/async_ddp_param_gather_c_en.png" height="350px" width="880px" style="display:block;"></p> | 24 | +<p align="center"> <img src="../figures/async_ddp_param_gather_c_en.png" height="350px" width="880px"></p> |
| 25 | 25 | ||
| 26 | A comparison of the above flows reveals that after enabling --overlap-param-gather, communication and computation are fully parallelized, greatly improving computation-communication parallel efficiency and thus enhancing model training efficiency. | 26 | A comparison of the above flows reveals that after enabling --overlap-param-gather, communication and computation are fully parallelized, greatly improving computation-communication parallel efficiency and thus enhancing model training efficiency. |
| 27 | 27 | ||
| @@ -31,35 +31,27 @@ This feature is designed for data-parallel training scenarios, particularly wher | |||
| 31 | 31 | ||
| 32 | ## Usage | 32 | ## Usage |
| 33 | 33 | ||
| 34 | -1. To enable weight update communication overlap, add the following parameters to the training configuration. | 34 | +* To enable weight update communication overlap, add the following parameters to the training configuration. |
| 35 | - | 35 | + `--overlap-param-gather` |
| 36 | - ```bash | 36 | +* Ensure the following two parameters are also enabled. |
| 37 | - --overlap-param-gather | 37 | + `--use-distributed-optimizer` |
| 38 | - ``` | 38 | + `--overlap-grad-reduce` |
| 39 | - | ||
| 40 | -2. Ensure the following two parameters are also enabled. | ||
| 41 | - | ||
| 42 | - ```bash | ||
| 43 | - --use-distributed-optimizer | ||
| 44 | - --overlap-grad-reduce | ||
| 45 | - ``` | ||
| 46 | 39 | ||
| 47 | ## Effects | 40 | ## Effects |
| 48 | 41 | ||
| 49 | Weight update communication overlap improves resource utilization and training efficiency in large-scale model training by enabling parallel execution of computation and communication tasks. This is reflected in the following aspects: | 42 | Weight update communication overlap improves resource utilization and training efficiency in large-scale model training by enabling parallel execution of computation and communication tasks. This is reflected in the following aspects: |
| 50 | 43 | ||
| 51 | -* Increased throughput\ | 44 | +* Increased throughput |
| 52 | Weight update communication overlap eliminates unnecessary waiting time in traditional synchronous modes. This optimization allows the system to process more data per unit of time, thereby significantly improving the overall system throughput. | 45 | Weight update communication overlap eliminates unnecessary waiting time in traditional synchronous modes. This optimization allows the system to process more data per unit of time, thereby significantly improving the overall system throughput. |
| 53 | 46 | ||
| 54 | -* Reduced latency\ | 47 | +* Reduced latency |
| 55 | The time required for a single iteration is reduced because computation and communication are no longer fully serialized but partially overlapped. This not only reduces the latency of individual training steps but also shortens the entire training cycle, increasing the speed from the start of training to deployment completion. | 48 | The time required for a single iteration is reduced because computation and communication are no longer fully serialized but partially overlapped. This not only reduces the latency of individual training steps but also shortens the entire training cycle, increasing the speed from the start of training to deployment completion. |
| 56 | 49 | ||
| 57 | -* Optimized resource usage\ | 50 | +* Optimized resource usage |
| 58 | Ensures that computing resources and communication bandwidth are utilized more efficiently. Traditional synchronization methods may leave computing nodes idle while waiting for other nodes to complete communication; this technique keeps hardware resources almost constantly active, greatly reducing idle waste caused by synchronization barriers. | 51 | Ensures that computing resources and communication bandwidth are utilized more efficiently. Traditional synchronization methods may leave computing nodes idle while waiting for other nodes to complete communication; this technique keeps hardware resources almost constantly active, greatly reducing idle waste caused by synchronization barriers. |
| 59 | 52 | ||
| 60 | -According to actual test data, when training a large language model such as LLAMA2-70B, applying the weight update communication overlap technique improved end-to-end performance by 3.4%. | 53 | +According to actual test data, when training a large language model such as LLAMA2 70B, applying the weight update communication overlap technique improved end-to-end performance by 3.4%. |
| 61 | 54 | ||
| 62 | -> [!NOTE] | 55 | +## Notes |
| 63 | -> | 56 | + |
| 64 | -> The native Megatron version has an issue with incorrect generation order, which causes the next round of forward computation to start early. After enabling this feature, to fix this issue, the initialization order of the attention layer is corrected to create `linear_qkv` first and then `linear_proj`. | 57 | +* The native Megatron version has an issue with incorrect generation order, which causes the next round of forward computation to start early. After enabling this feature, to fix this issue, the initialization order of the attention layer is corrected to create `linear_qkv` first and then `linear_proj`. |
| 65 | -> In legacy mode, `--overlap-param-gather` does not currently support being used together with `reuse_fp32_param`. | ||
| @@ -8,9 +8,9 @@ In large-model training, traditional [Megatron data parallelism](./data-parallel | |||
| 8 | 8 | ||
| 9 | To overcome this bottleneck, we introduce an asynchronous distributed data parallel (DDP) optimization mechanism. It decomposes computation and communication into finer-grained subtasks, enabling pipelined overlap of the two and significantly improving resource utilization. The core principle is illustrated below: | 9 | To overcome this bottleneck, we introduce an asynchronous distributed data parallel (DDP) optimization mechanism. It decomposes computation and communication into finer-grained subtasks, enabling pipelined overlap of the two and significantly improving resource utilization. The core principle is illustrated below: |
| 10 | 10 | ||
| 11 | -Figure 1 Asynchronous DDP computation | 11 | +### Figure 1 Asynchronous DDP computation |
| 12 | 12 | ||
| 13 | -<p align="left"> <img src="../figures/async_ddp_en.png" height="250px" width="680px" style="display:block;"></p> | 13 | +<p align="center"> <img src="../figures/async_ddp_en.png" height="250px" width="680px"></p> |
| 14 | 14 | ||
| 15 | Bucket mechanism: A temporary storage area (bucket) is set up to hold the gradients generated by backpropagation. Once the bucket reaches a preset capacity, the communication task for the internal gradients is triggered immediately, without waiting for all backward computations to complete. This mechanism allows subsequent backward computations to run in parallel with the current communication task, significantly improving the utilization of both computational and communication resources. | 15 | Bucket mechanism: A temporary storage area (bucket) is set up to hold the gradients generated by backpropagation. Once the bucket reaches a preset capacity, the communication task for the internal gradients is triggered immediately, without waiting for all backward computations to complete. This mechanism allows subsequent backward computations to run in parallel with the current communication task, significantly improving the utilization of both computational and communication resources. |
| 16 | 16 | ||
| @@ -23,11 +23,8 @@ Bucket mechanism: A temporary storage area (bucket) is set up to hold the gradie | |||
| 23 | ## Usage | 23 | ## Usage |
| 24 | 24 | ||
| 25 | Add the following parameters to the training script to activate the asynchronous DDP optimization algorithm. | 25 | Add the following parameters to the training script to activate the asynchronous DDP optimization algorithm. |
| 26 | - | 26 | +`--use-distributed-optimizer` |
| 27 | -```bash | 27 | +`--overlap-grad-reduce` |
| 28 | ---use-distributed-optimizer | ||
| 29 | ---overlap-grad-reduce | ||
| 30 | -``` | ||
| 31 | 28 | ||
| 32 | ## Effects | 29 | ## Effects |
| 33 | 30 | ||
| @@ -31,80 +31,9 @@ This feature is particularly suitable for the following scenarios: | |||
| 31 | 31 | ||
| 32 | ## Usage | 32 | ## Usage |
| 33 | 33 | ||
| 34 | -1. Add the parameter `--async-log-allreduce` to the startup bash script | 34 | +Add `--async-log-allreduce` to the training script; it is disabled by default. Use the loss interface of `pretrain_gpt.py`; there is no need to manually initiate the log all-reduce in `loss_func`. |
| 35 | -2. Replace the `loss_func` function in ``pretrain_gpt.py` as follows. | ||
| 36 | 35 | ||
| 37 | -```python | 36 | +The third return value of a custom loss function should be a metrics dictionary: each entry is either a two-element Tensor containing the "loss sum, token count" or a scalar Tensor that has already been reduced. The metric names and shapes must be consistent across different microbatches. |
| 38 | -def loss_func(loss_mask: torch.Tensor, output_tensor: torch.Tensor): | ||
| 39 | - """Loss function. | ||
| 40 | - | ||
| 41 | - Args: | ||
| 42 | - loss_mask (torch.Tensor): Used to mask out some portions of the loss | ||
| 43 | - output_tensor (torch.Tensor): The tensor with the losses | ||
| 44 | - | ||
| 45 | - Returns: | ||
| 46 | - the loss scalar for this micro-batch | ||
| 47 | - the number of non-padded tokens in this microbatch | ||
| 48 | - a dict containing reporting metrics on the loss and number of tokens across | ||
| 49 | - the data parallel ranks | ||
| 50 | - """ | ||
| 51 | - args = get_args() | ||
| 52 | - | ||
| 53 | - losses = output_tensor.float() | ||
| 54 | - loss_mask = loss_mask.view(-1).float() | ||
| 55 | - total_tokens = loss_mask.sum() | ||
| 56 | - loss = torch.cat([torch.sum(losses.view(-1) * loss_mask).view(1), total_tokens.view(1)]) | ||
| 57 | - | ||
| 58 | - if args.context_parallel_size > 1: | ||
| 59 | - torch.distributed.all_reduce(loss, group=mpu.get_context_parallel_group()) | ||
| 60 | - | ||
| 61 | - # Check individual rank losses are not NaN prior to DP all-reduce. | ||
| 62 | - rerun_state_machine = get_rerun_state_machine() | ||
| 63 | - if args.check_for_nan_in_loss_and_grad: | ||
| 64 | - rerun_state_machine.validate_result( | ||
| 65 | - result=loss[0], | ||
| 66 | - rejection_func=torch.isnan, | ||
| 67 | - message="found NaN in local forward loss calculation", | ||
| 68 | - tolerance=0.0, # forward pass calculations are deterministic | ||
| 69 | - fatal=True, | ||
| 70 | - ) | ||
| 71 | - rerun_state_machine.validate_result( | ||
| 72 | - result=loss[0], | ||
| 73 | - rejection_func=torch.isinf, | ||
| 74 | - message="found Inf in local forward loss calculation", | ||
| 75 | - tolerance=0.0, # forward pass calculations are deterministic | ||
| 76 | - fatal=True, | ||
| 77 | - ) | ||
| 78 | - # Check for spiky loss | ||
| 79 | - if args.check_for_spiky_loss: | ||
| 80 | - rerun_state_machine.validate_result( | ||
| 81 | - result=loss[0], | ||
| 82 | - rejection_func=partial( | ||
| 83 | - rerun_state_machine.is_unexpectedly_large, | ||
| 84 | - threshold=SPIKY_LOSS_FACTOR, | ||
| 85 | - context="loss", | ||
| 86 | - ), | ||
| 87 | - message="Spiky loss", | ||
| 88 | - tolerance=0.0, # forward pass calculations are deterministic | ||
| 89 | - fatal=False, | ||
| 90 | - ) | ||
| 91 | - # Reduce loss for logging. | ||
| 92 | - reporting_loss = loss.clone().detach() | ||
| 93 | - allreduce_handle = torch.distributed.all_reduce( | ||
| 94 | - reporting_loss, group=mpu.get_data_parallel_group(), async_op=True | ||
| 95 | - ) | ||
| 96 | - | ||
| 97 | - # loss[0] is a view of loss, so it has ._base not None, which triggers assert error | ||
| 98 | - # in core/pipeline_parallel/schedule.py::deallocate_output_tensor, calling .clone() | ||
| 99 | - # on loss[0] fixes this | ||
| 100 | - local_num_tokens = loss[1].clone().detach().to(torch.int) | ||
| 101 | - return ( | ||
| 102 | - loss[0].clone(), | ||
| 103 | - local_num_tokens, | ||
| 104 | - ({'lm loss': (reporting_loss[0], reporting_loss[1])}, allreduce_handle), | ||
| 105 | - ) | ||
| 106 | - | ||
| 107 | -``` | ||
| 108 | 37 | ||
| 109 | ## Effects | 38 | ## Effects |
| 110 | 39 | ||
| @@ -17,14 +17,14 @@ The auto settings feature relies entirely on data modeling derived from profilin | |||
| 17 | 17 | ||
| 18 | ### White-Box Search | 18 | ### White-Box Search |
| 19 | 19 | ||
| 20 | -- **Phase 1**: Launch auto settings on a small number of machines. This feature scales down the network size, generates multiple profiling configurations, and automatically launches them multiple times. These profiling runs are primarily used for black-box analysis, such as analyzing which tensors are partitioned, how the shapes of certain operators change, and which operators are added or removed when the configuration changes. After profiling is complete, the result files are parsed to extract the information needed for subsequent black-box modeling. | 20 | +- **Phase 1:** Launch auto settings on a small number of machines. This feature scales down the network size, generates multiple profiling configurations, and automatically launches them multiple times. These profiling runs are primarily used for black-box analysis, such as analyzing which tensors are partitioned, how the shapes of certain operators change, and which operators are added or removed when the configuration changes. After profiling is complete, the result files are parsed to extract the information needed for subsequent black-box modeling. |
| 21 | -- **Phase 2**: Perform black-box modeling based on the profiling results. For memory, it automatically analyzes how each tensor is partitioned under different configurations. For performance, it infers how operators are added or removed and how their shapes change with different configurations, and regresses the efficiency of intra-node and inter-node communication. In addition to basic performance and memory modeling, it also analyzes the performance and memory of each candidate recomputation module, enabling the subsequent search to estimate which modules should be selected for recomputation and their impact on performance and memory. | 21 | +- **Phase 2:** Perform black-box modeling based on the profiling results. For memory, it automatically analyzes how each tensor is partitioned under different configurations. For performance, it infers how operators are added or removed and how their shapes change with different configurations, and regresses the efficiency of intra-node and inter-node communication. In addition to basic performance and memory modeling, it also analyzes the performance and memory of each candidate recomputation module, enabling the subsequent search to estimate which modules should be selected for recomputation and their impact on performance and memory. |
| 22 | -- **Phase 3**: Search for configurations based on the models derived in Phase 2, providing the expected performance and memory for each configuration. This step also relies on an operator performance knowledge base to query the performance of operators with different shapes. Any unseen operators generated during profiling are added to the operator performance knowledge base. If the proportion of operators covered by the knowledge base for a given configuration falls below a threshold, an additional profiling run is launched. This profiling can also simulate large-scale scenarios with smaller setups by simultaneously reducing the network scale and parallelism parameters to obtain operators with the same shapes. If the operator coverage is insufficient to infer performance, the performance of the few uncovered operators is estimated through regression. After the search is complete, the top three configurations with the best performance that meet memory requirements are recommended. | 22 | +- **Phase 3:** Search for configurations based on the models derived in Phase 2, providing the expected performance and memory for each configuration. This step also relies on an operator performance knowledge base to query the performance of operators with different shapes. Any unseen operators generated during profiling are added to the operator performance knowledge base. If the proportion of operators covered by the knowledge base for a given configuration falls below a threshold, an additional profiling run is launched. This profiling can also simulate large-scale scenarios with smaller setups by simultaneously reducing the network scale and parallelism parameters to obtain operators with the same shapes. If the operator coverage is insufficient to infer performance, the performance of the few uncovered operators is estimated through regression. After the search is complete, the top three configurations with the best performance that meet memory requirements are recommended. |
| 23 | 23 | ||
| 24 | ### Black-Box Search | 24 | ### Black-Box Search |
| 25 | 25 | ||
| 26 | -- **Phase 1**: Same as Phase 1 of white-box search, performs modeling and pruning the search space. | 26 | +- **Phase 1:** Same as Phase 1 of white-box search, performs modeling and pruning the search space. |
| 27 | -- **Phase 2**: Profiles each configuration in the search space to obtain the corresponding memory usage, operator time, and communication time, thereby selecting the most suitable configuration. | 27 | +- **Phase 2:** Profiles each configuration in the search space to obtain the corresponding memory usage, operator time, and communication time, thereby selecting the most suitable configuration. |
| 28 | 28 | ||
| 29 | ### Mixed Search | 29 | ### Mixed Search |
| 30 | 30 | ||
| @@ -48,7 +48,7 @@ Supported features: | |||
| 48 | - [x] ZeRO1 | 48 | - [x] ZeRO1 |
| 49 | - [x] VPP | 49 | - [x] VPP |
| 50 | - [x] CP (ring attention) | 50 | - [x] CP (ring attention) |
| 51 | -- [x] EP (DeepSpeed-MOE) | 51 | +- [x] EP (Deepspeed-MOE) |
| 52 | - [x] MicroBatchSize | 52 | - [x] MicroBatchSize |
| 53 | - [x] Token rearrangement | 53 | - [x] Token rearrangement |
| 54 | - [x] Recomputation | 54 | - [x] Recomputation |
| @@ -75,7 +75,7 @@ Add the following configuration to the parameter list of the training script to | |||
| 75 | --target-nnodes $NNODES \ # Number of nodes launched for profiling, consistent with the baseline training script | 75 | --target-nnodes $NNODES \ # Number of nodes launched for profiling, consistent with the baseline training script |
| 76 | --nproc-per-node $GPUS_PER_NODE \ # Number of processes running on each node, typically equal to the number of devices per node, consistent with the baseline training script | 76 | --nproc-per-node $GPUS_PER_NODE \ # Number of processes running on each node, typically equal to the number of devices per node, consistent with the baseline training script |
| 77 | --master-addr $MASTER_ADDR \ # Master node IP, keep consistent with the baseline training script | 77 | --master-addr $MASTER_ADDR \ # Master node IP, keep consistent with the baseline training script |
| 78 | ---master-port 6005 \ # Master node port, set a port different from the baseline script | 78 | +--master-port 6005 # Master node port, set a port different from the baseline script |
| 79 | --node-rank $NODE_RANK \ # Keep consistent with the baseline training script | 79 | --node-rank $NODE_RANK \ # Keep consistent with the baseline training script |
| 80 | ``` | 80 | ``` |
| 81 | 81 | ||
| @@ -1,48 +0,0 @@ | |||
| 1 | -# Automated Pipeline Parallelism | ||
| 2 | - | ||
| 3 | -## Background and challenges | ||
| 4 | - | ||
| 5 | -Pipeline parallelism (PP) partitions the model network layers into multiple stages and maps these stages to different devices, enabling different devices to compute different parts of the neural network in parallel. Pipeline parallelism significantly alleviates the memory bottleneck of a single card and improves hardware utilization through pipelined training across multiple cards. Pipeline parallelism has become one of the most commonly used parallelism approaches for large model training. However, current pipeline parallelism is not optimal in terms of memory consumption and performance, with two major issues: | ||
| 6 | - | ||
| 7 | -1. Memory imbalance: Under the commonly used scheduling mode (1F1B) in current pipeline parallelism, the memory usage of pipeline stages closer to the front layers of the model is far greater than that of the later stages, with a difference of 2 to 3 times. Overall, the trainable model scale is limited by the memory consumption of PP-Stage 0. | ||
| 8 | - | ||
| 9 | -2. Pipeline bubble: The pipeline 1F1B scheduling strategy alternately performs forward and backward computation of micro-batch data on each device. Due to imbalanced computational loads among pipeline devices or fluctuations in network communication, waiting occurs between devices (pipeline bubble), which affects training performance. | ||
| 10 | - | ||
| 11 | -## Solution | ||
| 12 | - | ||
| 13 | -This system is based on online profiling and PP modeling search. By enabling the memory optimization module and the performance optimization module, it maximizes the memory and performance of pipeline parallelism training, respectively. The memory optimization module aims to automatically find the optimal layer distribution for stages in pipeline parallelism and a fine-grained recomputation module, evenly distributing the memory on each card, optimizing PP-Stages with memory bottlenecks, and achieving peak reduction. The performance optimization module employs automatic optimization of the mbs sequence and forward-backward scheduling sequence, along with a multi-stream asynchronous communication mechanism, to compress pipeline bubbles and improve training performance. | ||
| 14 | - | ||
| 15 | -### Memory Optimization Module | ||
| 16 | - | ||
| 17 | -Based on online profiling and PP modeling search, it automatically constructs an optimal memory layout scheme to balance memory overhead across stages, achieving peak reduction while minimizing end-to-end training time, with good ease of use and generalizability. Specifically, it automatically optimizes the memory layout scheme within the joint search space of layer distribution and fine-grained recomputation: | ||
| 18 | - | ||
| 19 | -1. PP layer distribution partitioning: An uneven layer partitioning strategy is adopted to automatically search for the optimal layer partitioning method, balancing the memory consumed by each card, thereby optimizing PP-Stages with memory bottlenecks and achieving peak reduction. | ||
| 20 | -2. Fine-grained recomputation: Pipeline bubble time is utilized for recomputation to ensure no performance degradation. By automatically optimizing a fine-grained recomputation strategy, peak memory is further reduced. | ||
| 21 | - | ||
| 22 | -### Performance Optimization Module | ||
| 23 | - | ||
| 24 | -Under the condition that the peak training memory overhead does not exceed the maximum memory capacity of the device, the end-to-end training time is minimized by automatically finding the optimal mbs sequence and forward-backward scheduling sequence in pipeline parallelism. | ||
| 25 | - | ||
| 26 | -1. Dynamic mbs: Under a given gbs, the optimal mbs sequence is automatically searched. A small mbs is used to accelerate the startup and cool down of the pipeline, compressing the bubble time. During the steady phase, the most efficient mbs is automatically found for computation, shortening the steady-phase computation time and improving end-to-end training performance. | ||
| 27 | -2. Forward and backward scheduling: By adjusting the order of forward and backward computations during pipeline parallelism and combining it with a multi-stream asynchronous communication mechanism, the steady-phase bubble of the pipeline is compressed, thereby improving training performance. | ||
| 28 | - | ||
| 29 | -The PP automatic parallelism system is illustrated in the following figure: | ||
| 30 | - | ||
| 31 | -<p align="center"> <img src="../figures/auto_pipeline_parallel_en.png"></p> | ||
| 32 | - | ||
| 33 | -## Use Scenario | ||
| 34 | - | ||
| 35 | -This system is primarily used in training scenarios where pipeline parallelism is enabled. Using the PP automatic parallelism system can effectively optimize issues of insufficient memory or an excessively large proportion of pipeline bubbles. | ||
| 36 | -**Usage Conditions:** | ||
| 37 | - | ||
| 38 | -1. `--pipeline-model-parallel-size >= 2`; | ||
| 39 | -2. The memory optimization and performance optimization modules cannot be used simultaneously. | ||
| 40 | - | ||
| 41 | -## Usage | ||
| 42 | - | ||
| 43 | -1. When memory is insufficient, the PP automatic parallelism memory optimization module can be enabled. First, add the `--automated-pipeline` flag to the training script to enable the feature. | ||
| 44 | -2. When the pipeline bubble is too large, resulting in suboptimal training performance, the PP automatic parallelism performance optimization module can be enabled. First, add the `--automated-pipeline-perf` flag to the training script to enable the feature. | ||
| 45 | - | ||
| 46 | -## Effects | ||
| 47 | - | ||
| 48 | -The PP automatic parallelism memory optimization module reduces average peak memory usage by 11.5% for Llama-2-7b, -13b, and -70b models under PP training, with less than 1% performance degradation. Meanwhile, the performance optimization module delivers an average 7.6% performance gain for Llama-2-7b, -13b, and -70b models under the same PP setup. | ||
| @@ -8,30 +8,30 @@ Mixture of Experts (MoE) models scale model capacity by routing input tokens to | |||
| 8 | 8 | ||
| 9 | This feature designs a dynamic and adaptive load balancing mechanism for expert parallelism. Its core idea combines "data finding computation" with "computation finding data," achieving mutual optimization of computation and parameters through dynamic decision-making to attain load balancing. The specific implementation includes the following key innovations: | 9 | This feature designs a dynamic and adaptive load balancing mechanism for expert parallelism. Its core idea combines "data finding computation" with "computation finding data," achieving mutual optimization of computation and parameters through dynamic decision-making to attain load balancing. The specific implementation includes the following key innovations: |
| 10 | 10 | ||
| 11 | -- Real-time monitoring and decision-making: During the forward propagation process, global token distribution information is obtained through the router. | 11 | +- **Real-time monitoring and decision-making**: During the forward propagation process, global token distribution information is obtained through the router. |
| 12 | -- Dynamic hot expert selection: Based on global load information, the subset of experts with the heaviest load is dynamically identified as "hot experts". | 12 | +- **Dynamic hot expert selection**: Based on global load information, the subset of experts with the heaviest load is dynamically identified as "hot experts". |
| 13 | -- Parameter broadcast and sharing: Through cross-node broadcast operations, it is ensured that all expert parallelism (EP) nodes hold the latest copies of hot expert parameters, achieving parameter sharing. | 13 | +- **Parameter broadcast and sharing**: Through cross-node broadcast operations, it is ensured that all expert parallelism (EP) nodes hold the latest copies of hot expert parameters, achieving parameter sharing. |
| 14 | -- Token distribution optimization: The token distribution strategy is restructured to convert tokens originally destined for remote hot experts into local computation, thereby reducing communication overhead. | 14 | +- **Token distribution optimization**: The token distribution strategy is restructured to convert tokens originally destined for remote hot experts into local computation, thereby reducing communication overhead. |
| 15 | -- Computation-communication overlap and pipeline masking: In pipeline parallelism, the forward and backward computation phases of different micro-batches are finely scheduled to achieve complete masking of expert parallelism communication. | 15 | +- **Computation-communication overlap and pipeline masking**: In pipeline parallelism, the forward and backward computation phases of different micro-batches are finely scheduled to achieve complete masking of expert parallelism communication. |
| 16 | 16 | ||
| 17 | This solution employs a dynamic decision-making mechanism that combines "data finding computation" and "computation finding data" to achieve intelligent mutual discovery between computation and parameters, ultimately attaining load balancing and improving system throughput and resource utilization. | 17 | This solution employs a dynamic decision-making mechanism that combines "data finding computation" and "computation finding data" to achieve intelligent mutual discovery between computation and parameters, ultimately attaining load balancing and improving system throughput and resource utilization. |
| 18 | 18 | ||
| 19 | ## Use Scenario | 19 | ## Use Scenario |
| 20 | 20 | ||
| 21 | -This feature is applicable to the following scenarios. (**It is strongly recommended to enable it only when both of the following conditions are met simultaneously. Otherwise, you may not achieve performance gains or may even experience performance degradation.**) | 21 | +This feature is applicable to the following scenarios. **It is strongly recommended to enable it only when both of the following conditions are met simultaneously; otherwise, you may not achieve performance gains or may even experience performance degradation**: |
| 22 | 22 | ||
| 23 | -- Large-scale EP training | 23 | +1. **Large-scale expert parallelism (EP) training**: |
| 24 | - - EP ≥ 32: The benefit of this feature is positively correlated with the scale of expert parallelism. When the EP value is small, the degree of load imbalance is relatively limited, and the additional overhead introduced by enabling this feature, such as parameter broadcasting, may outweigh its benefits. When the EP value is large, the load imbalance problem is typically more pronounced, and the performance improvement achieved through optimization with this feature is also more significant. | 24 | + - **The original EP configuration is relatively large (e.g., ≥32)**: The benefit of this feature is positively correlated with the scale of expert parallelism. When the EP value is small, the degree of load imbalance is relatively limited, and the additional overhead introduced by enabling this feature, such as parameter broadcasting, may outweigh its benefits. **When the EP value is large**, the load imbalance problem is typically more pronounced, and the performance improvement achieved through optimization with this feature is also more significant. |
| 25 | 25 | ||
| 26 | -- Significant load imbalance | 26 | +2. **Significant load imbalance**: |
| 27 | - - During actual training, dynamic changes in input data distribution cause some experts to receive far more tokens than others, creating obvious computation and communication hotspots. In such scenarios, redistributing computation tasks through dynamic load balancing yields the greatest benefits. | 27 | + - During actual training, dynamic changes in input data distribution cause **some experts to receive far more tokens than others**, creating obvious computation and communication hotpots. In such scenarios, redistributing computation tasks through dynamic load balancing yields the greatest benefits. |
| 28 | 28 | ||
| 29 | -Scenarios not recommended or with limited benefits: | 29 | +**Scenarios not recommended or with limited benefits**: |
| 30 | 30 | ||
| 31 | -- Small EP configurations (≤ 8) with relatively uniform load: The additional communication overhead may offset the benefits of load balancing. | 31 | +- **Small EP configurations (e.g., ≤ 8) with relatively uniform load**: The additional communication overhead may offset the benefits of load balancing. |
| 32 | -- Configurations that fail to meet any of the usage restrictions described below. | 32 | +- Configurations that **fail to meet any of the "usage restrictions" described below**. |
| 33 | -- Scenarios requiring strictly deterministic training: This feature involves dynamic decision-making and asynchronous communication, and does not guarantee binary alignment or complete determinism. | 33 | +- **Scenarios requiring strictly deterministic training**: This feature involves dynamic decision-making and asynchronous communication, and **does not guarantee binary alignment or complete determinism**. |
| 34 | -- In the DSKv3 reduced-layer 4-node Atlas A3 scenario, the loss error is less than 1%. For small-scale model scenarios, errors caused by accumulation order may be amplified, so this feature is not recommended. | 34 | +- In the DSKv3 reduced-layer 4-node Atlas A3 scenario, the loss error is less than 1%. **For small-scale model scenarios, errors caused by accumulation order may be amplified, so this feature is not recommended.** |
| 35 | 35 | ||
| 36 | ## Usage | 36 | ## Usage |
| 37 | 37 | ||
| @@ -41,79 +41,94 @@ Users can enable the expert-parallel dynamic load balancing algorithm by adding | |||
| 41 | --balanced-moe-experts --balanced-moe-hot-expert-num N --trans-hot-expert-group-num M | 41 | --balanced-moe-experts --balanced-moe-hot-expert-num N --trans-hot-expert-group-num M |
| 42 | ``` | 42 | ``` |
| 43 | 43 | ||
| 44 | -**Usage Restrictions** | 44 | +**Parameter Description:** |
| 45 | + | ||
| 46 | +- `--balanced-moe-experts`: **Master switch** for enabling the dynamic load balancing algorithm. | ||
| 47 | +- `--balanced-moe-hot-expert-num <N>`: Specifies the number of hot experts `N` (a positive integer) dynamically maintained per layer. Based on this parameter and the real-time load status, the system selects the `N` experts with the highest load for parameter broadcast and load balancing scheduling. | ||
| 48 | + - **Default value:** `3` | ||
| 49 | + - **Important recommendations and restrictions:** | ||
| 50 | + 1. `N` **must be less than or equal to the number of local experts on each EP rank**. The formula for calculating the number of local experts is: `num_local_experts = num_experts / expert_model_parallel_size`. For example, if the total number of experts is 64 and the EP degree is 8, each rank has 8 local experts, and the maximum value for `--balanced-moe-hot-expert-num` can only be set to `8`. | ||
| 51 | + 2. Setting `N` too large (exceeding the number of local experts) not only provides no additional benefit, but also increases unnecessary parameter broadcast overhead and memory usage, **potentially degrading performance**. It is recommended to set `N` based on the actual degree of load imbalance (typically between 3 and 8) to strike a balance between overhead and benefit. | ||
| 52 | + | ||
| 53 | +- `--trans-hot-expert-group-num <M>`: Specifies the number of groups `M` (a positive integer) when transmitting hot expert parameters. This controls the concurrency of hot expert parameter broadcast, helping to reduce communication time. | ||
| 54 | + - **Default value:** `3` | ||
| 55 | + - **Important restriction:** `M` must satisfy: **1 ≤ M ≤ N** (where `N` is the value of `--balanced-moe-hot-expert-num`). | ||
| 56 | + | ||
| 57 | +## Usage Restrictions | ||
| 45 | 58 | ||
| 46 | To ensure the stable operation and performance of EP dynamic load balancing, the following usage restrictions and configuration requirements must be strictly observed: | 59 | To ensure the stable operation and performance of EP dynamic load balancing, the following usage restrictions and configuration requirements must be strictly observed: |
| 47 | 60 | ||
| 48 | -- Dependency feature requirements | 61 | +### 1. Dependency feature requirements |
| 49 | - - `--moe-fb-overlap` must be enabled simultaneously. | ||
| 50 | - - `--moe-grouped-gemm` must be enabled to support GroupedMatmul. | ||
| 51 | 62 | ||
| 52 | -- Dispatcher support | 63 | +- `--moe-fb-overlap` **must be enabled simultaneously**. |
| 53 | - - Currently only the `--moe-token-dispatcher-type=alltoall` dispatcher type is supported. | 64 | +- `--moe-grouped-gemm` **must be enabled** to support GroupedMatmul. |
| 54 | - - `allgather` and `alltoall_seq` dispatcher types are not supported. | ||
| 55 | 65 | ||
| 56 | -- Parallel configuration restrictions | 66 | +### 2. Dispatcher support |
| 57 | - - `--expert-tensor-parallel-size=1` needs to be set. Expert tensor parallelism is not supported. | ||
| 58 | - - `--overlap-grad-reduce` must be disabled; asynchronous data-parallel communication hiding is not supported. | ||
| 59 | 67 | ||
| 60 | -- Memory and model configuration | 68 | +- Currently only the `--moe-token-dispatcher-type=alltoall` dispatcher type is supported. |
| 61 | - - Only `--moe-zero-memory=level0` is supported for memory optimization. | 69 | +- `allgather` and `alltoall_seq` dispatcher types are **not supported**. |
| 62 | - - `moe-zero-memory-num-layers` is not supported. | ||
| 63 | - - Only Mcore architecture models are supported. Ensure that `--use_legacy_models` is disabled. | ||
| 64 | 70 | ||
| 65 | -- MoE mode restrictions | 71 | +### 3. Parallel configuration restrictions |
| 66 | - - Only Dropless mode is supported; Megatron MoE's Token Drop & Pad functionality is not supported. | ||
| 67 | - - It is not recommended to enable `--swap-attention` simultaneously, as it may cause performance degradation. | ||
| 68 | 72 | ||
| 69 | -- Pipeline parallel restrictions | 73 | +- `--expert-tensor-parallel-size=1` needs to be set. **Expert tensor parallelism is not supported**. |
| 70 | - - When using Virtual Pipeline Parallel (VPP), the following conditions must be met: | 74 | +- `--overlap-grad-reduce` must be disabled; **asynchronous data-parallel communication hiding is not supported**. |
| 71 | - - The global batch size (GBS) must satisfy: GBS > 1 × Data Parallelism (DP) × Pipeline Parallelism (PP) × Micro Batch Size (MBS). | ||
| 72 | - - If noop layers are used, they must be placed at the last VPP stage at the tail of the model. | ||
| 73 | 75 | ||
| 74 | -- Conflicts | 76 | +### 4. Memory and model configuration |
| 75 | - he following features conflict with the EP dynamic load balancing algorithm and cannot be enabled simultaneously: | ||
| 76 | - - `--moe-alltoall-overlap-comm` | ||
| 77 | - - `--moe-hierarchical-alltoallv` | ||
| 78 | - - `--recompute-in-advance` | ||
| 79 | - - `--recompute-in-bubble` | ||
| 80 | 77 | ||
| 81 | -- Parameter configuration restrictions | 78 | +- Only `--moe-zero-memory=level0` is supported for memory optimization. |
| 82 | - - `--balanced-moe-hot-expert-num` must be less than or equal to the number of local experts per EP rank (`num_experts / expert_model_parallel_size`). | 79 | +- `moe-zero-memory-num-layers` is **not supported**. |
| 83 | - - `--trans-hot-expert-group-num` must satisfy `1 ≤ M ≤ N`, where `N` is the value of`--balanced-moe-hot-expert-num`. | 80 | +- Only Mcore architecture models are supported. Ensure that `--use_legacy_models` is disabled. |
| 84 | 81 | ||
| 85 | -- Non-deterministic behavior notice | 82 | +### 5. MoE mode restrictions |
| 86 | - **Important: This feature is not binary-aligned.** | ||
| 87 | - - Fundamental change in computation path: | ||
| 88 | - - Forward propagation path changes: After enabling this feature, tokens that were originally sent to remote hot experts are computed locally, fundamentally altering the execution path of the computation graph. | ||
| 89 | - - Gradient accumulation order changes: Gradients for hot experts are computed in parallel across multiple EP ranks and asynchronously reduced, altering the gradient accumulation order. | ||
| 90 | - - Impact of non-associative floating-point arithmetic: | ||
| 91 | - - Due to the non-associative nature of floating-point addition, changing the distribution order of tokens across different devices leads to slight differences in intermediate results during forward and backward propagation. | ||
| 92 | - - Even mathematically equivalent operations like `(A+B)+C` and `A+(B+C)` may yield different results in floating-point representation. | ||
| 93 | - - Specific manifestations of non-binary alignment: | ||
| 94 | - - Inconsistent across runs: Even with the deterministic computation flag `--npu-deterministic` enabled, running the same training twice may not produce bit-level identical results. | ||
| 95 | - - Applicable scenario restrictions: | ||
| 96 | - - Absolutely not applicable: Scenarios that require strict bit-level reproducibility. | ||
| 97 | 83 | ||
| 98 | -**Parameter Description** | 84 | +- Only Dropless mode is supported; Megatron MoE's Token Drop & Pad functionality is **not supported**. |
| 85 | +- It is not recommended to enable `--swap-attention` simultaneously, as it may cause performance degradation. | ||
| 99 | 86 | ||
| 100 | -- `--balanced-moe-experts`: Master switch for enabling the dynamic load balancing algorithm. | 87 | +### 6. Pipeline parallel restrictions |
| 101 | -- `--balanced-moe-hot-expert-num <N>`: Specifies the number of hot experts `N` (a positive integer) dynamically maintained per layer. Based on this parameter and the real-time load status, the system selects the `N` experts with the highest load for parameter broadcast and load balancing scheduling. | ||
| 102 | - - Default value: `3` | ||
| 103 | - - Important recommendations and restrictions: | ||
| 104 | - 1. `N` must be less than or equal to the number of local experts on each EP rank. The formula for calculating the number of local experts is: `num_local_experts = num_experts / expert_model_parallel_size`. For example, if the total number of experts is 64 and the EP degree is 8, each rank has 8 local experts, and the maximum value for `--balanced-moe-hot-expert-num` can only be set to `8`. | ||
| 105 | - 2. Setting `N` too large (exceeding the number of local experts) not only provides no additional benefit, but also increases unnecessary parameter broadcast overhead and memory usage, potentially degrading performance. It is recommended to set `N` based on the actual degree of load imbalance (typically between 3 and 8) to strike a balance between overhead and benefit. | ||
| 106 | 88 | ||
| 107 | -- `--trans-hot-expert-group-num <M>`: Specifies the number of groups `M` (a positive integer) when transmitting hot expert parameters. This controls the concurrency of hot expert parameter broadcast, helping to reduce communication time. | 89 | +When using Virtual Pipeline Parallel (VPP), the following conditions must be met: |
| 108 | - - Default value: `3` | 90 | + |
| 109 | - - Important restriction: `M` must satisfy: `1 ≤ M ≤ N` (where `N` is the value of `--balanced-moe-hot-expert-num`). | 91 | +- The global batch size (GBS) must satisfy: **GBS > 1 × Data Parallelism (DP) × Pipeline Parallelism (PP) × Micro Batch Size (MBS)**. |
| 92 | +- If noop layers are used, they **must** be placed at the last VPP stage at the tail of the model. | ||
| 93 | + | ||
| 94 | +### 7. Conflicts | ||
| 95 | + | ||
| 96 | +The following features conflict with the EP dynamic load balancing algorithm and **cannot be enabled simultaneously**: | ||
| 97 | + | ||
| 98 | +- `--moe-alltoall-overlap-comm` | ||
| 99 | +- `--moe-hierarchical-alltoallv` | ||
| 100 | +- `--recompute-in-advance` | ||
| 101 | +- `--recompute-in-bubble` | ||
| 102 | + | ||
| 103 | +### 8. Parameter configuration restrictions | ||
| 104 | + | ||
| 105 | +- `--balanced-moe-hot-expert-num` **must be less than or equal to** the number of local experts per EP rank (`num_experts / expert_model_parallel_size`). | ||
| 106 | +- `--trans-hot-expert-group-num` **must satisfy**: **1 ≤ M ≤ N** (where `N` is the value of `--balanced-moe-hot-expert-num`). | ||
| 107 | + | ||
| 108 | +### 9. Non-deterministic behavior notice | ||
| 109 | + | ||
| 110 | +**Important: This feature is not binary-aligned.** | ||
| 111 | + | ||
| 112 | +1. **Fundamental change in computation path**: | ||
| 113 | + - **Forward propagation path changes**: After enabling this feature, tokens that were originally sent to remote hot experts are computed locally, fundamentally altering the execution path of the computation graph. | ||
| 114 | + - **Gradient accumulation order changes**: Gradients for hot experts are computed in parallel across multiple EP ranks and asynchronously reduced, altering the gradient accumulation order. | ||
| 115 | + | ||
| 116 | +2. **Impact of non-associative floating-point arithmetic**: | ||
| 117 | + - Due to the **non-associative nature of floating-point addition**, changing the distribution order of tokens across different devices leads to slight differences in intermediate results during forward and backward propagation. | ||
| 118 | + - Even mathematically equivalent operations like `(A+B)+C` and `A+(B+C)` may yield different results in floating-point representation. | ||
| 119 | + | ||
| 120 | +3. **Specific manifestations of non-binary alignment**: | ||
| 121 | + - **Inconsistent across runs**: Even with the deterministic computation flag `--npu-deterministic` enabled, running the same training twice may not produce bit-level identical results. | ||
| 122 | + | ||
| 123 | +4. **Applicable scenario restrictions**: | ||
| 124 | + - **Absolutely not applicable**: Scenarios that require strict bit-level reproducibility. | ||
| 110 | 125 | ||
| 111 | ## Effects | 126 | ## Effects |
| 112 | 127 | ||
| 113 | -In an expert-parallel training environment that meets the recommended usage scenarios (large EP scale and load imbalance) and is correctly configured enabling this feature can achieve the following optimization effects: | 128 | +In an expert-parallel training environment that **meets the recommended usage scenarios** (large EP scale and load imbalance) and is **correctly configured**, enabling this feature can achieve the following optimization effects: |
| 114 | 129 | ||
| 115 | -- Load balancing optimization: Through the "computation-parameter mutual seeking" mechanism, the computational load is dynamically migrated from overloaded "hot experts" to idle experts, balancing the computational load across expert nodes and alleviating system bottlenecks. | 130 | +- **Load balancing optimization**: Through the "computation-parameter mutual seeking" mechanism, the computational load is dynamically migrated from overloaded "hot experts" to idle experts, balancing the computational load across expert nodes and alleviating system bottlenecks. |
| 116 | -- Effectively improved system throughput: By converting remote hot expert tokens that originally required cross-device communication into local computations, the data volume of All-to-All communication is significantly reduced. Meanwhile, fine-grained computation-communication overlap and pipeline scheduling effectively mask the latency of newly introduced communications such as parameter broadcasting, thereby accelerating training iteration speed. | 131 | +- **Effectively improved system throughput**: By converting remote hot expert tokens that originally required cross-device communication into local computations, the data volume of All-to-All communication is significantly reduced. Meanwhile, fine-grained computation-communication overlap and pipeline scheduling effectively mask the latency of newly introduced communications such as parameter broadcasting, thereby accelerating training iteration speed. |
| 117 | -- Improved hardware resource utilization: It reduces the time during which some devices are overloaded while others remain idle due to load imbalance, enabling all computing units to be utilized more fully and improving overall cluster efficiency. | 132 | +- **Improved hardware resource utilization**: It reduces the time during which some devices are overloaded while others remain idle due to load imbalance, enabling all computing units to be utilized more fully and improving overall cluster efficiency. |
| 118 | 133 | ||
| 119 | -Typical performance gains: Under conditions of the recommended scenarios (EP ≥ 32, significant load imbalance) and with proper configuration, this feature can deliver substantial end-to-end training throughput improvement. Conversely, if the recommended scenarios are not met or the configuration is improper, it may fail to yield gains or even cause performance degradation. | 134 | +**Typical performance gains**: Under conditions of the **recommended scenarios** (EP ≥ 32, significant load imbalance) and with proper configuration, this feature can deliver substantial end-to-end training throughput improvement. **Conversely, if the recommended scenarios are not met or the configuration is improper, it may fail to yield gains or even cause performance degradation**. |
| @@ -0,0 +1,9 @@ | |||
| 1 | +# get_batch Configuration Cache | ||
| 2 | + | ||
| 3 | +Caches the `TransformerConfig` constructed inside `get_batch`, reducing the host overhead caused by repeatedly creating the configuration. | ||
| 4 | + | ||
| 5 | +## Usage | ||
| 6 | + | ||
| 7 | +Add `--cache-get-batch-config` to the training script. Disabled by default. | ||
| 8 | + | ||
| 9 | +The adapter locates the training entry from the `forward_step_func` passed to `pretrain`. The entry must provide both `get_batch` and `core_transformer_config_from_args`; only configuration construction initiated directly by that `get_batch` is cached. The cache is distinguished by the args object, the configuration class, the MLA switch, and the heterogeneous layer configuration path, and does not cache data batches. | ||
| @@ -10,11 +10,11 @@ By splitting computation and communication tasks into finer-grained subtasks to | |||
| 10 | 10 | ||
| 11 | ### Approach | 11 | ### Approach |
| 12 | 12 | ||
| 13 | -#### Python script side implementation | 13 | +#### Python Script Implementation |
| 14 | 14 | ||
| 15 | Further split the tensor (into 2/4/8 parts), and use Python scripts to achieve parallelism between computation and communication for each sub-tensor, thereby increasing the utilization of computation and communication streams. | 15 | Further split the tensor (into 2/4/8 parts), and use Python scripts to achieve parallelism between computation and communication for each sub-tensor, thereby increasing the utilization of computation and communication streams. |
| 16 | 16 | ||
| 17 | -#### Fused operator implementation | 17 | +#### Fused Operator Implementation |
| 18 | 18 | ||
| 19 | Based on the MTE remote memory access capability, a fused large kernel approach is used to split computation and communication tasks into finer-grained sub-tasks within the operator implementation, achieving mutual pipeline overlap. | 19 | Based on the MTE remote memory access capability, a fused large kernel approach is used to split computation and communication tasks into finer-grained sub-tasks within the operator implementation, achieving mutual pipeline overlap. |
| 20 | 20 | ||
| @@ -59,13 +59,13 @@ ATB installation method: | |||
| 59 | --coc-fused-kernel # Note: Currently only supports TP=8. | 59 | --coc-fused-kernel # Note: Currently only supports TP=8. |
| 60 | ``` | 60 | ``` |
| 61 | 61 | ||
| 62 | -The environment variable for the fused operator has a higher priority, meaning that when `--coc-parallel-num` and `--coc-fused-kerne` are enabled simultaneously, `--coc-parallel-num` does not take effect. | 62 | +The environment variable for the fused operator has a higher priority, meaning that when `--coc-parallel-num` > 1 and `--coc-fused-kernel` is enabled, the former does not take effect. |
| 63 | 63 | ||
| 64 | ## CFG Customization Method | 64 | ## CFG Customization Method |
| 65 | 65 | ||
| 66 | You can customize the `coc_cfgs` dictionary in `mindspeed/core/tensor_parallel/lcal_coc/user_config.py` to customize part of the CoC configuration. | 66 | You can customize the `coc_cfgs` dictionary in `mindspeed/core/tensor_parallel/lcal_coc/user_config.py` to customize part of the CoC configuration. |
| 67 | 67 | ||
| 68 | -Only applicable to the CoC enabled through Python scripts" | 68 | +Only applicable to the CoC enabled through Python scripts. |
| 69 | 'matmul_soc_friendly': Whether to perform transpose/padding operations on the input matmul tensors so that they enter the Matmul operator with an NPU-friendly shape, thereby achieving a certain performance gain. Defaults to True; | 69 | 'matmul_soc_friendly': Whether to perform transpose/padding operations on the input matmul tensors so that they enter the Matmul operator with an NPU-friendly shape, thereby achieving a certain performance gain. Defaults to True; |
| 70 | 'customized_coc': Customizes the number of COC splits for matmul of a specified shape. Defaults to `{}`. If you need to set the number of CoC splits for a matmul of a specified shape to 1 (disable COC) or a value different from `coc-parallel-num`, you can follow this example: | 70 | 'customized_coc': Customizes the number of COC splits for matmul of a specified shape. Defaults to `{}`. If you need to set the number of CoC splits for a matmul of a specified shape to 1 (disable COC) or a value different from `coc-parallel-num`, you can follow this example: |
| 71 | 'customized_coc': {"[16384, 5120, 1920]": 8, "[16384, 1920, 5120]": 1} | 71 | 'customized_coc': {"[16384, 5120, 1920]": 8, "[16384, 1920, 5120]": 1} |
| @@ -86,4 +86,4 @@ Currently incompatible with the `--use-ascend-mc2` feature. | |||
| 86 | 86 | ||
| 87 | MoE models are not yet supported. | 87 | MoE models are not yet supported. |
| 88 | 88 | ||
| 89 | -This feature is supported by Atlas A2/A3 training products, while Ascend 950 products do not support enabling fused operators. | 89 | +This feature is fully supported by Atlas A2 training products/Atlas A3 training products, while Ascend 950PR&950DT products do not support enabling fused operators. |
| @@ -1,47 +0,0 @@ | |||
| 1 | -# compress-activation | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -As the sequence length increases, the proportion of video memory occupied by activations gradually grows, leading to excessively high peak memory per card. | ||
| 6 | - | ||
| 7 | -Therefore, we developed a memory compression feature based on the self-developed Ascend lossless compression operator to compress the memory occupied by activations, with no loss in precision. When there is a need to reduce peak memory, you can enable the following three switches to activate the memory compression feature. | ||
| 8 | - | ||
| 9 | -- Feature 1: `--compress-dense` compresses the activations generated by the first linear layer in the MLP module. | ||
| 10 | -- Feature 2: `--compress-activation` compresses the activation generated by the selected transformer layer. | ||
| 11 | -- Feature 3: `--compress-optimizer` compresses the first/second-order momentum of the optimizer. | ||
| 12 | - | ||
| 13 | -## Solution | ||
| 14 | - | ||
| 15 | -- Feature 1: | ||
| 16 | -Record the MLP execution order of the first node, and use a multi-stream asynchronous method to call the Ascend lossless compression operator to compress the activation generated by the MLP module in the Dense layer. Since this operator uses vector computing power, it can overlap with Cube computation and communication, so the compression and decompression processes themselves generally do not cause performance degradation. The specific method is shown in the following figure: | ||
| 17 | - | ||
| 18 | - | ||
| 19 | -- Feature 2: | ||
| 20 | -Records the execution order of the transformer layer on each device and performs lossless compression on the activations generated within the layer. The Ascend lossless compression operator is called asynchronously through a multi-stream approach to compress memory. Since this operator uses vector computing power, it can overlap with Cube computation and communication, meaning the compression and decompression processes themselves cause almost no performance degradation. The specific process is shown in the following figure: | ||
| 21 | - | ||
| 22 | - | ||
| 23 | -- Feature 3: | ||
| 24 | -Directly calls the Ascend lossless compression operator to perform unhidden compression on the first-order and second-order momentum of the AdamW optimizer, which introduces a slight performance degradation. | ||
| 25 | - | ||
| 26 | -## Application Scenario | ||
| 27 | - | ||
| 28 | -Applicable to scenarios for training large models with insufficient training memory. | ||
| 29 | - | ||
| 30 | -## Usage | ||
| 31 | - | ||
| 32 | -- Feature 1: | ||
| 33 | - `--compress-dense level0` performs only vector compression, saving less space with minimal performance overhead. | ||
| 34 | - `--compress-dense level1` performs vector compression while swapping some results to the CPU, saving more space but incurring additional performance overhead. | ||
| 35 | -- Feature 2: | ||
| 36 | -`--compress-activation` indicates which layers' generated activations to compress. It can be configured as `1-3` or `1,2,3`, indicating compression of activations generated by layers 1/2/3. It can be configured as `1-3,5-8,10`, indicating compression of activations generated by layers 1/2/3/5/6/7/8/10. It can also be configured as `0` to indicate compression of all layers. The default value is NULL. | ||
| 37 | -- Feature 3: | ||
| 38 | -`--compress-optimizer` Whether to compress the first/second-order momentum of the optimizer. The default value is False. | ||
| 39 | - | ||
| 40 | -## Effects | ||
| 41 | - | ||
| 42 | -Using the activation compression feature reduces peak memory. Using the optimizer first/second-order momentum compression feature introduces a slight additional performance degradation because the compression/decompression process is not overlapped. For typical models such as Llama and Qwen, enabling Feature 1/Feature 2 yields average memory savings of 3%/7%. For example, with the Qwen3-8b model at a sequence length of 8192 and a parallel configuration of PP4TP2CP1, enabling Feature 2 achieves a memory saving of 6.2%. | ||
| 43 | - | ||
| 44 | -## Usage Constraints | ||
| 45 | - | ||
| 46 | -- Feature 2 is an iterative version of Feature 1, and the two cannot be enabled simultaneously. Feature 3 can be enabled simultaneously with either Feature 1 or Feature 2. | ||
| 47 | -- Currently incompatible with the `recompute_activation_function` feature. | ||
| @@ -1,69 +0,0 @@ | |||
| 1 | -# KV Cache Optimization in Context Parallelism | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -The context parallelism (CP) feature splits the sequence along the sequence dimension before attention computation. During attention computation, the full sequence needs to be calculated, so CP communication occurs during attention computation. | ||
| 6 | - | ||
| 7 | -1. During attention computation, Ring CP cyclically receives KV from other cards via send/recv, ultimately ensuring that Q can attend to the full KV and maintaining mathematical equivalence with the non-split case. Currently, KV is discarded after forward computation completes, and send/recv is required again during the backward pass to retrieve KV. When computing with short sequences, communication time may exceed computation time, making it impossible for computation time to hide communication time, thereby degrading performance. Therefore, optimization is needed for scenarios where computation time is insufficient to hide communication time, in order to accelerate training in such cases. | ||
| 8 | - | ||
| 9 | -2. In the Ulysses CP scheme under Grouped Query Attention (GQA) models, after enabling TP, each rank typically has only one head. In this case, the communication volume of All2All is the same as that of AllGather. However, when there is only one head, the All2All scheme requires repeating KV. When the data layout is typically sbh or sbnd, repeating along the h dimension results in non-contiguous addresses, leading to operator efficiency issues and requiring additional operations such as transpose. In contrast, AllGather operates directly on the s dimension with contiguous addresses, requiring no extra operations. | ||
| 10 | - | ||
| 11 | -3. In Ulysses CP, when repeat operations occur, the Key and Value tensors passed into the attention backward pass are expanded by a factor of CP in memory compared to the Key and Value tensors before the repeat. This leads to increased memory consumption and may cause out-of-memory situations. | ||
| 12 | - | ||
| 13 | -## Solution | ||
| 14 | - | ||
| 15 | -1. Add a KV cache feature on top of Ring Attention long-sequence parallelism. You can choose to cache all K and V, cache only K, or set up a hierarchical cache. During the forward pass of long-sequence parallelism, the KV tensors received in the forward computation are retained until the backward computation, allowing gradient results to be computed directly and reducing communication time. | ||
| 16 | - | ||
| 17 | -2. For GQA models with a single head per rank, add an AllGather KV + All2All Q approach on top of Ulysses Attention long-sequence parallelism. This reduces repeat operations and the overhead of non-contiguous memory operations such as transpose, thereby improving training performance. | ||
| 18 | - | ||
| 19 | -3. Add a KV cache feature to the All2All and AllGather approaches in Ulysses. You can choose to cache all K and V, cache only K, or set up a hierarchical cache. During the forward pass, the KV tensors before communication are cached and retained until the backward pass, where communication is re-executed for computation, saving memory. The All2All approach can only enable KV caching when repeat operations are performed. | ||
| 20 | - | ||
| 21 | -### Approach | ||
| 22 | - | ||
| 23 | -1. In the Ring scheme, the sequence is split into CP parts for parallel computation, with each rank computing its own K and V while simultaneously sending and receiving K and V from other ranks. For example, rank 0 sends K0/V0 and K7/V7 to the "downstream" rank while receiving K3/V3 and K4/V4 from the "upstream" rank. Each card repeats the same action CP-1 times, so that ultimately each split sequence can "attend to" the global KV and compute the complete attention result. The backward computation logic follows the same principle: initially each rank has its own KV, and after computing its own gradient, the subsequent steps send the received K and V chunks along with dK and dV to other ranks, while simultaneously receiving K, V chunks, dK, and dV chunks from other ranks, using the received K and V as input to compute and update gradients, thereby achieving overlap of computation and communication. | ||
| 24 | -A key point in the backward process is that inter-rank communication requires sending four data blocks—K, V, dK, and dV—for a total of CP-1 times. Since K and V are already sent and received sequentially among ranks during the forward pass, caching K and V during the forward pass will halve the backward communication time. When CP is relatively large, caching all K and V increases memory pressure. By supporting caching only a portion of K and V, or caching once every N layers, flexible configuration on demand is enabled. | ||
| 25 | - | ||
| 26 | -2. In a GQA model with a single head, the AllGather KV communication method is used to replace the original Repeat-All2All KV method for obtaining the full sequence, while the All2All scheme is still used for Q. | ||
| 27 | - | ||
| 28 | -3. In the Ulysses scheme, the KV before the Repeat-All2All or AllGather communication in the forward pass is cached and carried to the backward pass, and the post-communication KV is used for computation to ensure correctness. In the backward pass, when the KV from before the Repeat-All2All or AllGather communication is retrieved, the KV undergoes Repeat-All2All or AllGather re-communication for gradient computation. Since re-communication incurs performance loss, a portion of K and V can be cached, or caching can be performed once every N layers, flexibly combined to achieve optimal performance within memory constraints. | ||
| 29 | - | ||
| 30 | -The flexible caching strategy is as follows: | ||
| 31 | - | ||
| 32 | -1. Support configuring the layer interval for caching K and V: partial caching of K and V can be achieved by caching across different layers, controlled by adding a parameter `interval` to specify the interval of layers to cache. For example, when `interval=1`, K and V will be cached in layers numbered 0, 2, 4, ..., and so on. The cache interval supports starting from 0 and must not exceed the number of layers on the rank. The default value of the interval is 0. | ||
| 33 | - | ||
| 34 | -2. Support caching a portion of K and V: on each layer, caching only K (K and V have the same size) is supported. This method is controlled by a parameter. When the parameter value is `half`, only K is cached; when configured as `full`, both K and V are cached. The default is to cache both K and V. This configuration and the layer interval-based cache configuration can be enabled simultaneously. The caching effects after configuration are cumulative and do not conflict with each other. | ||
| 35 | - | ||
| 36 | -## Application Scenario | ||
| 37 | - | ||
| 38 | -When long sequence parallelism is enabled during training. | ||
| 39 | - | ||
| 40 | -`FlashAttention` is required, and it is enabled by default. | ||
| 41 | - | ||
| 42 | -To benefit from the KV cache in Ring Attention, the computation time must be less than the communication time. Theoretically, the sequence length assigned to each computation block must satisfy `c < F/B`, where `F` is the FLOPS of each device and `B` is the bandwidth between devices. | ||
| 43 | - | ||
| 44 | -In Ulysses Attention, to benefit from AllGather KV + All2All Q, a GQA model is required, and the communication volume must be the same, meaning KV has only one head. | ||
| 45 | - | ||
| 46 | -In Ulysses Attention, to benefit from the KV cache, the Repeat-All2All approach requires the use of repeat to achieve memory savings, while AllGather KV + All2All Q can achieve memory savings as soon as CP is enabled. | ||
| 47 | - | ||
| 48 | -## Usage | ||
| 49 | - | ||
| 50 | -| Important Parameter | Parameter Description | | ||
| 51 | -|------------------------------------------------|----------------------------------------------------------| | ||
| 52 | -| `--context-parallel-kv-cache-policy [full/half]` | Enables KV caching and sets its level during CP forward computation. Default is `full`, which caches both K and V; `half` caches only K. | | ||
| 53 | -| `--context-parallel-cache-interval [int]` | Sets the layer interval for KV caching during CP forward computation. Default is `0`, meaning every layer is cached. Configure based on user requirements. | | ||
| 54 | -| `--use-ulysses-allgather-kv` | Enables the AllGather scheme for Ulysses Attention. Default is `False`, meaning it is not enabled. | | ||
| 55 | - | ||
| 56 | -## Effects | ||
| 57 | - | ||
| 58 | -In scenarios where computation time cannot hide communication time in Ring Attention, enabling the KV cache feature will shorten training time and improve training performance, but it will increase memory usage. | ||
| 59 | - | ||
| 60 | -Enabling AllGather KV in Ulysses Attention will, in permissible scenarios, shorten training time and improve training performance. | ||
| 61 | - | ||
| 62 | -Enabling KV cache in Ulysses Attention will reduce memory usage when Repeat is applied in Repeat-All2All, but it will cause performance degradation. In the AllGather case, memory usage will also be reduced, but performance may drop compared to the AllGather scheme without caching. | ||
| 63 | - | ||
| 64 | -## Notes | ||
| 65 | - | ||
| 66 | -1. When enabling `--context-parallel-kv-cache-policy`, context parallelism must also be enabled; otherwise, the feature is not supported. | ||
| 67 | -2. When enabling `--context-parallel-cache-interval`, `--context-parallel-kv-cache-policy` must also be enabled, and the `interval` value must be less than the number of layers; otherwise, the feature is not supported. | ||
| 68 | -3. When enabling `--use-ulysses-allgather-kv`, context parallelism must be enabled, `--context-parallel-algo` must be set to `ulysses_cp_algo`, `--group-query-attention` must be enabled, and the number of KV heads per rank must be 1; otherwise, the feature is not supported. | ||
| 69 | -4. When both `--context-parallel-kv-cache-policy` and `--context-parallel-algo ulysses_cp_algo` are enabled, the KV repeat condition must be satisfied (i.e., the number of KV heads must be less than the CP world size, and the number of query heads must be divisible by the number of KV heads). Otherwise, the feature is not supported. KV repeat is typically satisfied automatically when using GQA. | ||
| @@ -1,46 +0,0 @@ | |||
| 1 | -# conv3d Sequence Parallelism | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -In model architectures for fields such as multimodal and machine vision, conv3d modules are often used for 3D convolution operations on feature maps. In large models, the time consumed by convolution operations increases as the scale of the feature map grows. | ||
| 6 | -Since the convolution process for each block of the feature map is executed sequentially, there is actually no dependency constraint on the execution order among the blocks. In distributed training, 3D convolution operations need to be parallelized to improve convolution speed. | ||
| 7 | - | ||
| 8 | -## Solution | ||
| 9 | - | ||
| 10 | -Construct a `Conv3DSequenceParallel` class that splits the input feature map along the depth dimension of the convolution kernel and then performs parallel convolution. | ||
| 11 | - | ||
| 12 | -- **Forward process**: | ||
| 13 | - Construct the `Conv3DSequenceParallel` class, split the input feature map along the depth dimension of the convolution kernel, distribute it to different process groups for conv3d 3D convolution operations, and perform a gather operation on the convolution results before outputting them to downstream modules.<br> | ||
| 14 | -- **Backward process**: | ||
| 15 | - The `Conv3DSequenceParallel` class performs a split operation on the gradients obtained from downstream backward propagation, splitting the gradients along the depth dimension, distributing them to parallel 3D convolution modules for backward propagation, and then performing a gather operation on the backward gradients from the parallel 3D convolution modules before outputting them to upstream modules. | ||
| 16 | - | ||
| 17 | - | ||
| 18 | -## Application Scenario | ||
| 19 | - | ||
| 20 | -Applicable to training models that contain conv3d (non-padding mode) modules. | ||
| 21 | - | ||
| 22 | -## Usage | ||
| 23 | - | ||
| 24 | -Replace the original conv3d module with `Conv3DSequenceParallel` and specify the relevant parameters to achieve parallel acceleration.<br> | ||
| 25 | -The `Conv3DSequenceParallel` module interface is as follows:<br> | ||
| 26 | - | ||
| 27 | -`Conv3DSequenceParallel(pg, in_channels, out_channels, kernel_size, stride, dilation, bias, param_async, dtype, sp_size)` | ||
| 28 | - | ||
| 29 | -- `pg`: Required input. Data type: `torch.distributed.ProcessGroup`. Specifies the communication process group. | ||
| 30 | -- `in_channels`: Required input. Data type: `int`. Specifies the number of input channels. | ||
| 31 | -- `out_channels`: Required input. Data type: `int`. Specifies the number of output channels. | ||
| 32 | -- `kernel_size`: Optional attribute. Data type: `tuple(int, int, int)`. Default value: `(1, 1, 1)`. Specifies the convolution kernel size. | ||
| 33 | -- `stride`: Optional attribute. Data type: `tuple(int, int, int)`. Default value: `(1, 1, 1)`. Specifies the convolution stride size for each dimension. | ||
| 34 | -- `dilation`: Optional attribute. Data type: `int` or `tuple(int, int, int)`. Default value: `1`. Specifies the dilation rate. | ||
| 35 | -- `bias`: Optional attribute. Data type: `bool`. Default value: `True`. Indicates whether bias is enabled. | ||
| 36 | -- `param_async`: Optional attribute. Data type: `bool`. Default value: `False`. Indicates whether asynchronous parameter communication is enabled. | ||
| 37 | -- `dtype`: Optional attribute. Data type: `torch.dtype`. Default value: `torch.bfloat16`. Specifies the data type of the convolution layer. | ||
| 38 | -- `sp_size`: Optional attribute. Data type: `int`. Default value: `1`. Specifies the sequence parallel size. | ||
| 39 | - | ||
| 40 | -## Effects | ||
| 41 | - | ||
| 42 | -Distributes the convolution operations of each convolution region to process groups for parallel execution, improving the efficiency of 3D convolution. | ||
| 43 | - | ||
| 44 | -## Notes | ||
| 45 | - | ||
| 46 | -The `Conv3DSequenceParallel` module does not support padding mode. Therefore, conv3d modules that use padding cannot be replaced with the `Conv3DSequenceParallel` module. | ||
| @@ -2,86 +2,69 @@ | |||
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | -As model weights grow, training requires more efficient use of device memory. ZeRO-1 shards optimizer states across the DP group, while model weights and gradients still occupy substantial persistent memory. FSDP also shards weights and gradients to reduce persistent training-state memory per DP rank. | 5 | +As large model weights increase, there is a need to further improve memory utilization efficiency. ZeRO-1 only shards the optimizer states within the DP domain, and model weights and gradients still occupy a large amount of persistent memory. FSDP further shards weights and gradients to reduce the persistent training-state memory of each DP rank. |
| 6 | 6 | ||
| 7 | -This document describes the basic Megatron FSDP adaptation in `core_r0.18.0`, rather than PyTorch FSDP2. | 7 | +This document describes the basic adaptation of Megatron FSDP in `core_r0.18.0`, not PyTorch FSDP2. |
| 8 | 8 | ||
| 9 | ## Solution | 9 | ## Solution |
| 10 | 10 | ||
| 11 | -With `optim_grads_params`, each DP rank keeps a parameter shard. When forward or backward computation requires full parameters, an All Gather collects them across the DP group. Full parameters are released according to the upstream buffer lifecycle when no longer needed. Reduce Scatter reduces and shards backward gradients, and each rank updates its parameters using local gradient shards. | 11 | +Under the `optim_grads_params` strategy, each DP rank persistently holds a parameter shard. When the forward and backward computations require complete parameters, an All Gather is performed within the DP domain; after the computation ends, the complete parameters that are no longer needed are released according to the upstream buffer lifecycle. The backward gradients are reduced and sharded via Reduce Scatter, and each rank uses its local gradient shard to update the corresponding parameters. |
| 12 | 12 | ||
| 13 | -The 0.18 adaptation uses the new gradient bucket reduction pipeline and preserves communication dtype conversion, double buffering, and asynchronous release. HCCL reduce-scatter uses separate output storage. In the SUM path, gradients are scaled once before communication without relying on NCCL premultiplied SUM. The MoE router follows the 0.18 implementation, preserving bias and router dtype support. | 13 | +The 0.18 adaptation uses the new gradient bucket reduction pipeline and preserves communication dtype conversion, double buffering, and asynchronous release. The HCCL path uses separate reduce-scatter output storage. In the SUM path, gradients are scaled once before communication without relying on NCCL premultiplied SUM. The MoE router follows the 0.18 implementation, preserving its bias and router dtype support. |
| 14 | 14 | ||
| 15 | ## Application Scenario | 15 | ## Application Scenario |
| 16 | 16 | ||
| 17 | -Use FSDP when DP > 1 and weights, gradients, and optimizer states occupy substantial device memory that can be reduced by further sharding. | 17 | +When DP > 1, the model weights, gradients, and optimizer states occupy a large amount of memory, and you want to further shard these training states. |
| 18 | 18 | ||
| 19 | ## Usage | 19 | ## Usage |
| 20 | 20 | ||
| 21 | -1. Enable Megatron FSDP with the following configuration: | 21 | +1. Enable Megatron FSDP and add the following configuration: |
| 22 | 22 | ||
| 23 | - ```bash | 23 | +```bash |
| 24 | --use-megatron-fsdp | 24 | --use-megatron-fsdp |
| 25 | - --data-parallel-sharding-strategy optim_grads_params | 25 | +--data-parallel-sharding-strategy optim_grads_params |
| 26 | - --no-gradient-accumulation-fusion | 26 | +--no-gradient-accumulation-fusion |
| 27 | - --use-distributed-optimizer | 27 | +--use-distributed-optimizer |
| 28 | --ckpt-format fsdp_dtensor | 28 | --ckpt-format fsdp_dtensor |
| 29 | - ``` | 29 | +``` |
| 30 | 30 | ||
| 31 | - The legacy `--use-custom-fsdp` flag from master remains supported and is mapped to `--use-megatron-fsdp` before Megatron argument validation. The default checkpoint format in 0.18 is `torch_dist`; Megatron FSDP requires explicitly selecting `fsdp_dtensor`. Changing this option does not convert existing checkpoints. | 31 | + The legacy `--use-custom-fsdp` from master remains supported and is mapped to `--use-megatron-fsdp` before Megatron argument validation. The Core 0.18 checkpoint default is `torch_dist`, and Megatron FSDP must explicitly use `fsdp_dtensor`; changing the format argument does not automatically convert existing checkpoints. |
| 32 | 32 | ||
| 33 | -2. Unset `CUDA_DEVICE_MAX_CONNECTIONS` after loading the environment setup script: | 33 | +2. After loading the environment script, unset `CUDA_DEVICE_MAX_CONNECTIONS`: |
| 34 | 34 | ||
| 35 | ```bash | 35 | ```bash |
| 36 | unset CUDA_DEVICE_MAX_CONNECTIONS | 36 | unset CUDA_DEVICE_MAX_CONNECTIONS |
| 37 | ``` | 37 | ``` |
| 38 | 38 | ||
| 39 | -3. When using `--moe-grouped-gemm` from the existing MoE example, also specify: | 39 | +3. When using `--moe-grouped-gemm` in the existing MoE test case, you must also specify: |
| 40 | 40 | ||
| 41 | ```bash | 41 | ```bash |
| 42 | --transformer-impl transformer_engine | 42 | --transformer-impl transformer_engine |
| 43 | ``` | 43 | ``` |
| 44 | 44 | ||
| 45 | -4. Install a TransformerEngineNPU version containing the DTensor FusedAdam fix, such as commit [5c85c0d](https://gitcode.com/GuoHaifeng1999/TransformerEngineNPU/commit/5c85c0df3e9c1887a4aa5a000f96b2f01d9fb031), and verify that the training process imports that installation. Older TENPU versions reject DTensor parameters; changing the checkpoint format alone does not resolve this optimizer error. | 45 | +4. Install a TransformerEngineNPU version containing the DTensor FusedAdam fix, such as a version containing commit [5c85c0d](https://gitcode.com/GuoHaifeng1999/TransformerEngineNPU/commit/5c85c0df3e9c1887a4aa5a000f96b2f01d9fb031), and verify that the training environment actually imports that installation package. Older TENPU versions reject the DTensor parameters provided by FSDP; only adjusting the checkpoint format cannot resolve the optimizer type error. |
| 46 | 46 | ||
| 47 | -## Support and Validation Status | 47 | +## Support Scope and Validation Status |
| 48 | 48 | ||
| 49 | | Item | Current adaptation | | 49 | | Item | Current adaptation | |
| 50 | -|------|--------------------| | 50 | +|------|--------------| |
| 51 | -| Basic FSDP | Megatron FSDP in Core 0.18 is integrated; the existing script uses `optim_grads_params` | | 51 | +| Basic FSDP | 0.18 Megatron FSDP is integrated; the existing script uses `optim_grads_params` | |
| 52 | -| Parameters and gradients | The matching TENPU version supports unquantized FP32/FP16/BF16 DTensor parameters, ordinary and decoupled gradients, and empty local shards | | 52 | +| Parameters and gradients | With the matching TENPU, supports unquantized FP32/FP16/BF16 DTensor parameters, as well as ordinary gradients, decoupled gradients, and empty shard handling | |
| 53 | -| Optimizer states | The matching TENPU version supports floating-point moments and the existing FP32/FP16 master-weight paths | | 53 | +| Optimizer states | With the matching TENPU, supports floating-point moments, as well as FP32/FP16 master weights under the existing conditions | |
| 54 | -| Communication lifecycle | Upstream communication dtype, double buffering, and asynchronous release are preserved; target NPU validation remains necessary | | 54 | +| Communication lifecycle | Upstream communication dtype, double buffering, and asynchronous release are preserved; validation on the target NPU environment is required | |
| 55 | -| HSDP/HFSDP and AVG | Upstream branches are retained with separate RS outputs; multi-device combinations remain unverified | | 55 | +| HSDP/HFSDP and AVG | Upstream branches are retained and adapted for separate RS outputs; multi-device combination validation has not yet been completed | |
| 56 | -| Quantization and remainders | The TENPU DTensor path does not support quantized model parameters, FP8/uint8 moments, or INT16 parameter remainders | | 56 | +| Quantization and remainder | The current TENPU DTensor path does not support quantized model parameters, FP8/uint8 moments, or INT16 parameter remainder | |
| 57 | -| Checkpoints | Existing `fsdp_dtensor` save/load paths are integrated; real multi-device save/restore and recovery with a different DP size remain unverified | | 57 | +| Checkpoints | The existing `fsdp_dtensor` save/load path is integrated; real multi-device save/restore and recovery with a changed DP size still need validation | |
| 58 | -| Feature combinations | Arbitrary combinations with other repository features are not guaranteed; training accuracy and performance of the existing MoE script also require validation on multiple Ascend devices | | 58 | +| Feature combinations | Arbitrary combinations with other features in the repository are not guaranteed; the training accuracy and performance of the existing MoE script also need validation in a multi-device Ascend environment | |
| 59 | 59 | ||
| 60 | -Integration means that the basic source adaptation is complete, rather than that every configuration has passed NPU end-to-end tests. TENPU CPU local-shard checks do not replace HCCL training or real checkpoint recovery validation. | 60 | +The above "integrated" means that the basic adaptation of the source code is complete; it does not mean that all combinations have passed NPU end-to-end tests. TENPU's CPU local-shard validation cannot replace HCCL training and real checkpoint recovery validation. |
| 61 | - | ||
| 62 | -## AG stream and start-sync prefetch optimization | ||
| 63 | - | ||
| 64 | -To align memory behavior with the master branch, enable `--fsdp-memory-compatibility` to apply both optimizations below. The option defaults to false and requires Megatron FSDP with optimization level >= 2. | ||
| 65 | - | ||
| 66 | -```bash | ||
| 67 | ---use-megatron-fsdp \ | ||
| 68 | ---fsdp-memory-compatibility | ||
| 69 | -``` | ||
| 70 | - | ||
| 71 | -You can also enable FSDP with `--use-custom-fsdp`. See [Usage](#usage) above for the remaining configuration. | ||
| 72 | - | ||
| 73 | -### 1: Dynamic calling-stream AG | ||
| 74 | - | ||
| 75 | -MCore 0.18 creates a separate stream for parameter All Gather (AG). Using different streams for computation and AG can affect memory reuse by the caching allocator and increase reserved memory. | ||
| 76 | - | ||
| 77 | -When enabled, the option passes `ag_stream=None` to `AllGatherPipeline`, so each AG uses the NPU stream current at the time of the call. This avoids using a fixed separate AG stream or capturing a temporary initialization stream. The RS stream, HCCL internal communication streams, and HSDP outer AG stream retain their existing behavior. | ||
| 78 | - | ||
| 79 | -### 2: No extra start-sync prefetch | ||
| 80 | - | ||
| 81 | -`start_param_sync` can gather the first parameter bucket after an optimizer update and before the next forward pass. MCore 0.18 may also prefetch subsequent buckets at this stage, bringing full parameters into memory early and increasing peak memory. | ||
| 82 | - | ||
| 83 | -When enabled, the option sets `prefetch=False` for forward parameter gathering by the matching instance only during normal asynchronous `start_param_sync`. First-bucket gathering and its wait behavior are preserved to align start-sync behavior with master. Ordinary forward and backward prefetch, forced synchronization, the AG prefetch threshold, and RS queue capacity retain their existing behavior. | ||
| 84 | 61 | ||
| 85 | ## Effects | 62 | ## Effects |
| 86 | 63 | ||
| 87 | -Further sharding weights, gradients, and optimizer states can reduce persistent training-state memory. | 64 | +Sharding parameters, gradients, and optimizer states can reduce persistent training-state memory. Parameter all-gathers add communication, while separate reduce-scatter outputs and communication dtype conversion require temporary buffers. Measure peak memory and iteration time with the target model and parallel configuration. |
| 65 | + | ||
| 66 | +> [!NOTE] | ||
| 67 | +> | ||
| 68 | +> The existing [custom_fsdp.sh script](../../../tests_extend/system_tests/feature_tests/custom_fsdp.sh) from master is reused, and no new test cases are added. Modify the data and tokenizer paths before running it. | ||
| 69 | +> | ||
| 70 | +> The default script exits at iteration 50 but uses a save interval of 2000, and it includes `--no-load-optim` and `--no-load-rng`, so a single default run cannot demonstrate full checkpoint recovery. To validate recovery, configure save/load directories and an appropriate save interval in the same existing test, remove these two no-load options, and compare the next-step parameters, optimizer states, and loss after recovery. | ||
| @@ -9,10 +9,8 @@ When training models on large-scale datasets, a single computing device often ca | |||
| 9 | The data parallelism (DP) strategy divides the dataset into multiple batches and distributes them evenly across computing devices, so that each device is only responsible for processing a specific batch of data. | 9 | The data parallelism (DP) strategy divides the dataset into multiple batches and distributes them evenly across computing devices, so that each device is only responsible for processing a specific batch of data. |
| 10 | 10 | ||
| 11 | The implementation of this scheme requires the following two key elements: | 11 | The implementation of this scheme requires the following two key elements: |
| 12 | - | 12 | +The model structure and parameters deployed on each computing device must remain completely identical. |
| 13 | -- The model structure and parameters deployed on each computing device must remain completely identical. | 13 | +The data batches processed by each device must be different from one another, ensuring the parallelism and efficiency of the training process. |
| 14 | -- The data batches processed by each device must be different from one another, ensuring the parallelism and efficiency of the training process. | ||
| 15 | - | ||
| 16 | The overall approach of this scheme is as follows: | 14 | The overall approach of this scheme is as follows: |
| 17 | 15 | ||
| 18 | * Model replication: Store a complete model replica on each computing device. | 16 | * Model replication: Store a complete model replica on each computing device. |
| @@ -33,14 +31,14 @@ Enabling and configuring data parallelism primarily depends on the following met | |||
| 33 | * World size: The total number of NPUs participating in parallel training. | 31 | * World size: The total number of NPUs participating in parallel training. |
| 34 | * Tensor model parallel size: The number of parallel partitions for model weights. | 32 | * Tensor model parallel size: The number of parallel partitions for model weights. |
| 35 | * Pipeline model parallel size: The degree of pipeline parallelism for the model architecture. | 33 | * Pipeline model parallel size: The degree of pipeline parallelism for the model architecture. |
| 36 | -* Context parallel size: The parallel strategy for processing long sequence data. | 34 | +* Long sequence parallel size: The parallel strategy for processing long sequence data. |
| 37 | 35 | ||
| 38 | data_parallel_size = world_size // (tensor_model_parallel_size \* pipeline_model_parallel_size \* context_parallel_size) | 36 | data_parallel_size = world_size // (tensor_model_parallel_size \* pipeline_model_parallel_size \* context_parallel_size) |
| 39 | 37 | ||
| 40 | -> [!NOTE] | 38 | +### Notes |
| 41 | -> | 39 | + |
| 42 | -> The total number of model layers must be divisible by the pipeline parallelism size. | 40 | +* The total number of model layers must be divisible by the pipeline parallelism size. |
| 43 | -> `global_batch_size` must be divisible by `data_parallel_size`. | 41 | +* `global_batch_size` must be divisible by `data_parallel_size`. |
| 44 | 42 | ||
| 45 | ## Effects | 43 | ## Effects |
| 46 | 44 | ||
| @@ -0,0 +1,26 @@ | |||
| 1 | +# DeepSeek Sparse Attention (DSA) | ||
| 2 | + | ||
| 3 | +MindSpeed's DSA implementation based on Megatron-Core provides NPU sparse attention, Indexer, KL loss fusion operators, matrix absorption, and KVAllGather context parallelism adaptation. | ||
| 4 | + | ||
| 5 | +## Usage | ||
| 6 | + | ||
| 7 | +**Backend limitation:** `--transformer-impl transformer_engine` must be set, and `local` is not supported even when CP=1. | ||
| 8 | + | ||
| 9 | +Enable `--transformer-impl transformer_engine --experimental-attention-variant dsa --multi-latent-attention --qk-layernorm` in the model configuration. For MLA dimension configuration, see [MLA](multi-head-latent-attention.md). The Indexer uses Megatron's native `--dsa-indexer-head-dim`, `--dsa-indexer-n-heads`, `--dsa-indexer-topk`, and `--dsa-indexer-loss-coeff` arguments. | ||
| 10 | + | ||
| 11 | +The following MindSpeed switches are disabled by default; when all of them are disabled, the Megatron native DSA path is used. | ||
| 12 | + | ||
| 13 | +| Parameter | Effect and Constraint | | ||
| 14 | +| --- | --- | | ||
| 15 | +| `--use-fused-sparse-flash-attention` (P1) | NPU sparse attention; can be enabled on its own, but CP=1 is required in this case. | | ||
| 16 | +| `--use-fused-lightning-indexer` (P2) | NPU Indexer; must be enabled together with P1 and P3. | | ||
| 17 | +| `--use-fused-lightning-indexer-kl-loss` (P3) | NPU Indexer KL loss; must be enabled together with P1 and P2; `--num-attention-heads` only supports 32, 64, and 128. | | ||
| 18 | +| `--apply-rope-in-complex` | The Indexer uses complex-form RoPE; can be enabled independently of P1/P2/P3. | | ||
| 19 | +| `--use-dsa-absorb` | Use matrix absorption during training; can be enabled independently of P1/P2/P3. | | ||
| 20 | +| `--apply-rope-fusion` | Non-packed Indexer uses Ascend fused RoPE; when complex RoPE is also enabled, the Indexer preferentially uses the complex path. | | ||
| 21 | + | ||
| 22 | +When CP>1, set `--transformer-impl transformer_engine --cp-comm-type all_gather`, see [KVAllGather](kvallgather-context-parallel.md). The fusion path must enable P1/P2/P3 simultaneously; enabling P1 alone in combination with CP is not supported. `--eod-mask-loss` is not supported. | ||
| 23 | + | ||
| 24 | +## Checkpoint and Training | ||
| 25 | + | ||
| 26 | +The matrix absorption path splits the KV weights during training and merges them into the Megatron native KV layout in the checkpoint. The Indexer loss is normalized by micro-batch size. PP/VPP does not require additional DSA-specific pipeline switches. | ||
| @@ -0,0 +1,122 @@ | |||
| 1 | +# Deferring the Forward P2P Send Wait in VPP | ||
| 2 | + | ||
| 3 | +## Function and Principle | ||
| 4 | + | ||
| 5 | +When output pseudo-release is enabled, the interleaved pipeline schedule of Megatron Core 0.18 waits for the current | ||
| 6 | +forward send to complete before releasing. This step may establish a communication-to-computation dependency early, shrinking the overlap window between the P2P send and subsequent | ||
| 7 | +computation. | ||
| 8 | + | ||
| 9 | +MindSpeed's `defer-p2p-send-wait` defers the wait for the current send until after the next managed | ||
| 10 | +forward send is submitted; the last send is finalized when this schedule exits. The receive wait is still handled by the original schedule, | ||
| 11 | +and the computation order, communication content, and number of communications remain unchanged. | ||
| 12 | + | ||
| 13 | +This optimization targets the native VPP interleaved schedule on the NPU, and its main goal is to improve communication-computation overlap. | ||
| 14 | +It does not promise a reduction in peak memory, and it is not a memory optimization controlled by the MoE fast ops switch. | ||
| 15 | + | ||
| 16 | +## Usage | ||
| 17 | + | ||
| 18 | +`--defer-p2p-send-wait` is enabled by default and is an optimization level 2 feature. | ||
| 19 | +For it to actually take effect, `optimization_level >= 2` is required and all applicability conditions below must be met. | ||
| 20 | +Explicitly adding this parameter does not bypass the compatibility checks; use `--no-defer-p2p-send-wait` to disable it. | ||
| 21 | + | ||
| 22 | +The following is an example of a PP/VPP configuration added to an existing valid training command; the remaining model, parallelism, and training | ||
| 23 | +parameters still need to be set according to the actual task: | ||
| 24 | + | ||
| 25 | +```bash | ||
| 26 | +--optimization-level 2 \ | ||
| 27 | +--num-layers 16 \ | ||
| 28 | +--pipeline-model-parallel-size 2 \ | ||
| 29 | +--num-layers-per-virtual-pipeline-stage 4 | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +In this example, each PP rank has two virtual pipeline stages. Do not set another VPP/layout | ||
| 33 | +specification method at the same time, and do not add `--no-overlap-p2p-communication`. The final configuration must also satisfy | ||
| 34 | +`batch_p2p_comm=False` and `deallocate_pipeline_outputs=True`. | ||
| 35 | + | ||
| 36 | +When comparing the switch, keep the original configuration and add only the following to the disabled group: | ||
| 37 | + | ||
| 38 | +```bash | ||
| 39 | +--no-defer-p2p-send-wait | ||
| 40 | +``` | ||
| 41 | + | ||
| 42 | +## Applicability Conditions and Automatic Fallback | ||
| 43 | + | ||
| 44 | +After complete argument validation, the enabled state is retained only if all of the following conditions are met: | ||
| 45 | + | ||
| 46 | +| Condition | Requirement | | ||
| 47 | +| --- | --- | | ||
| 48 | +| Pipeline parallelism | `pipeline_model_parallel_size > 1` | | ||
| 49 | +| Virtual pipeline | Derived `virtual_pipeline_model_parallel_size > 0` | | ||
| 50 | +| P2P communication overlap | `overlap_p2p_comm=True` | | ||
| 51 | +| Batch P2P | `batch_p2p_comm=False` | | ||
| 52 | +| Output pseudo-release | `deallocate_pipeline_outputs=True` | | ||
| 53 | +| Schedule selection | `schedules_method=None`, using the native interleaved schedule | | ||
| 54 | +| Incompatible features | None of the switches below are enabled | | ||
| 55 | + | ||
| 56 | +The incompatible switches are: | ||
| 57 | + | ||
| 58 | +- `moe_fb_overlap` | ||
| 59 | +- `use_multiparameter_pipeline_model_parallel` | ||
| 60 | +- `recompute_in_bubble`, `recompute_in_advance` | ||
| 61 | +- `tp_2d` | ||
| 62 | +- `variable_seq_lengths` | ||
| 63 | +- `optimize_send_recv_comm` | ||
| 64 | +- `dist_train` | ||
| 65 | + | ||
| 66 | +When a condition is not met, the validation automatically sets `args.defer_p2p_send_wait` to `False` and continues | ||
| 67 | +with the original schedule. The PP/VPP values may use convertible numeric strings, and if they cannot be converted the feature is also disabled. | ||
| 68 | +For example, a configuration with PP2 but VPP not enabled does not apply this optimization. | ||
| 69 | + | ||
| 70 | +Patch installation occurs before complete argument validation. Registration only checks the user switch, to avoid treating a not-yet-derived VPP | ||
| 71 | +or an early string argument as incompatible. Each schedule entry reads the final switch once; when it is disabled, the original schedule is called directly, | ||
| 72 | +and the send is not taken over. | ||
| 73 | + | ||
| 74 | +During execution, when not in a managed schedule, when P2P overlap is not enabled, when there is no output to send, when the output is not | ||
| 75 | +a single NPU Tensor, or when the communication configuration uses batch P2P / disables output pseudo-release, this invocation | ||
| 76 | +goes directly through the original communication interface. | ||
| 77 | + | ||
| 78 | +The automatic fallback only handles these pre-determinable applicability conditions; it does not swallow errors in the original training configuration, nor does it | ||
| 79 | +catch exceptions after a send has already been submitted and re-execute the communication. | ||
| 80 | + | ||
| 81 | +## Lifecycle of the Send Storage | ||
| 82 | + | ||
| 83 | +Megatron's output pseudo-release replaces the `.data` of the output tensor. Saving only the same Tensor's | ||
| 84 | +Python reference cannot protect the original send storage, so the implementation manages asynchronous sends in the following order: | ||
| 85 | + | ||
| 86 | +1. Before submission, create independent Tensor metadata via `detach()` that holds the original storage; | ||
| 87 | + do not copy the send payload, and do not additionally hold its autograd graph. | ||
| 88 | +2. Call the original `send_forward_recv_forward` and take over the returned `send_next` Work. | ||
| 89 | + Remove only this item from the handles returned to the scheduler, and keep all receive waits. | ||
| 90 | +3. After the current send is submitted, call `wait()` on the previous managed send, and then release the corresponding holder. | ||
| 91 | + In normal steady-state operation, keep the most recent send; between submitting a new send and finalizing the previous one, two sends are briefly held. | ||
| 92 | +4. `Work.wait()` may only add an event dependency to the current NPU stream, so before discarding the holder, | ||
| 93 | + call `record_stream()` on the send tensor to protect the storage until the work on the related stream completes. | ||
| 94 | +5. When the schedule exits normally, returns from forward-only, or an exception occurs, finalize the remaining sends via `finally` | ||
| 95 | + and restore the schedule context. | ||
| 96 | + | ||
| 97 | +The normal path does not add any payload copies, communication calls, or full-device synchronizations. If the submission process throws an exception and fails to return | ||
| 98 | +a Work, the cleanup path uses a device synchronization to confirm the storage is safe; if the wait or cleanup fails, the error continues to propagate, | ||
| 99 | +and the related storage is retained until the process exits. An explicit error is also raised when the original interface does not return the expected `send_next` Work. | ||
| 100 | + | ||
| 101 | +## Validation and Performance Observation | ||
| 102 | + | ||
| 103 | +When comparing, fix the model, PP/VPP layout, number of microbatches, precision, recomputation configuration, and random seed, then run | ||
| 104 | +the default enabled group and the explicitly disabled group separately: | ||
| 105 | + | ||
| 106 | +- Check the value of `defer_p2p_send_wait` in the final arguments to confirm the optimization actually takes effect. | ||
| 107 | +- Compare the loss, gradients, or parameter updates to confirm the training results meet the tolerance of the precision in use. | ||
| 108 | +- After warmup, compare the steady-state step time and throughput; observe the overlap of the forward send and subsequent computation in the timeline. | ||
| 109 | +- Also record peak allocated / reserved. Extending the lifetime of the send storage may increase local | ||
| 110 | + memory usage, so you cannot infer a memory decrease or a guaranteed throughput improvement merely from the wait being deferred. | ||
| 111 | + | ||
| 112 | +The benefit depends on the pipeline layout, communication duration, and the amount of overlapable computation, and requires validation on actual multi-card NPUs. | ||
| 113 | + | ||
| 114 | +## Implementation Location | ||
| 115 | + | ||
| 116 | +- Argument and compatibility validation: | ||
| 117 | + [`defer_p2p_send_wait.py`](../../../mindspeed/features_manager/pipeline_parallel/defer_p2p_send_wait.py) | ||
| 118 | +- Schedule wrapping and send storage management: | ||
| 119 | + [`defer_p2p_send_wait.py`](../../../mindspeed/core/pipeline_parallel/defer_p2p_send_wait.py) | ||
| 120 | + | ||
| 121 | +The implementation is installed by MindSpeed on Megatron's schedule and P2P interfaces, and the patch does not need to be repeatedly | ||
| 122 | +installed in TENPU. | ||
| @@ -3,7 +3,6 @@ | |||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | In the traditional weight saving and loading process, specifically in scenarios where the `--ckpt-format torch` parameter is specified in the training script, each card holds a complete copy of the optimizer state. During the saving phase, each card saves the full optimizer state to disk, resulting in data redundancy. | 5 | In the traditional weight saving and loading process, specifically in scenarios where the `--ckpt-format torch` parameter is specified in the training script, each card holds a complete copy of the optimizer state. During the saving phase, each card saves the full optimizer state to disk, resulting in data redundancy. |
| 6 | - | ||
| 7 | To reduce the data redundancy of optimizer states, although enabling the distributed optimizer allows each card to hold only the sharded optimizer state, thereby reducing runtime memory overhead and the disk space occupied by saved weight files, this strategy introduces All-Gather operations during the saving phase and Scatter operations during the loading phase, thus increasing communication overhead. | 6 | To reduce the data redundancy of optimizer states, although enabling the distributed optimizer allows each card to hold only the sharded optimizer state, thereby reducing runtime memory overhead and the disk space occupied by saved weight files, this strategy introduces All-Gather operations during the saving phase and Scatter operations during the loading phase, thus increasing communication overhead. |
| 8 | 7 | ||
| 9 | ## Solution | 8 | ## Solution |
| @@ -19,11 +18,11 @@ Supports TP, PP, CP, EP, and VPP configuration scenarios as well as scenarios wh | |||
| 19 | - Specify `--ckpt-format torch_dist` and `--save <weight save path>` in the script to enable the distributed weight saving feature. The model will be saved as distributed weights during the saving phase. | 18 | - Specify `--ckpt-format torch_dist` and `--save <weight save path>` in the script to enable the distributed weight saving feature. The model will be saved as distributed weights during the saving phase. |
| 20 | - `--auto-detect-ckpt-format` is an optional parameter used to automatically detect the weight format for loading. When this parameter is used in a training script that specifies `--ckpt-format torch_dist` and `--load <weight load path>`, the loading phase will automatically detect whether the weights are in `--ckpt-format torch_dist` format or `--ckpt-format torch` format and load them accordingly. | 19 | - `--auto-detect-ckpt-format` is an optional parameter used to automatically detect the weight format for loading. When this parameter is used in a training script that specifies `--ckpt-format torch_dist` and `--load <weight load path>`, the loading phase will automatically detect whether the weights are in `--ckpt-format torch_dist` format or `--ckpt-format torch` format and load them accordingly. |
| 21 | 20 | ||
| 22 | -> [!NOTE] | 21 | +## Notes |
| 23 | -> | 22 | + |
| 24 | -> When loading weights generated in the `--ckpt-format torch_dist` format, specify the same `--ckpt-format` parameter, i.e., use `--ckpt-format torch_dist`. | 23 | +1. When loading weights generated in the `--ckpt-format torch_dist` format, specify the same `--ckpt-format` parameter, i.e., use `--ckpt-format torch_dist`. |
| 25 | -> `--ckpt-format torch_dist` has not yet been adapted for scenarios where MindSpeed features are enabled. | 24 | +2. `--ckpt-format torch_dist` has not yet been adapted for scenarios where MindSpeed features are enabled. |
| 26 | -> In CP scenarios, `--ckpt-format torch_dist` currently only supports `--context-parallel-algo` set to `megatron_cp_algo`. | 25 | +3. In CP scenarios, `--ckpt-format torch_dist` currently only supports `--context-parallel-algo` set to `megatron_cp_algo`. |
| 27 | 26 | ||
| 28 | ## Effects | 27 | ## Effects |
| 29 | 28 | ||
| @@ -15,10 +15,7 @@ When the DP size is greater than 1, the optimizer states are evenly distributed | |||
| 15 | ## Usage | 15 | ## Usage |
| 16 | 16 | ||
| 17 | To deploy the distributed optimizer, simply add the following configuration to your script: | 17 | To deploy the distributed optimizer, simply add the following configuration to your script: |
| 18 | - | 18 | +`--use-distributed-optimizer # Enable the distributed optimizer feature` |
| 19 | -```bash | ||
| 20 | ---use-distributed-optimizer # Enable the distributed optimizer feature | ||
| 21 | -``` | ||
| 22 | 19 | ||
| 23 | ## Effects | 20 | ## Effects |
| 24 | 21 | ||
| @@ -1,33 +0,0 @@ | |||
| 1 | -# Double Ring Attention Long-Sequence Parallelism | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -Training large language models on long sequences requires substantial memory and computational resources. The industry has proposed sequence parallelism methods based on head parallelism and context parallelism. In the attention block, the head parallelism approach retains the entire sequence and computes attention for different heads in parallel, while the context parallelism approach splits the QKV tensors into chunks along the sequence dimension. However, both approaches face limitations when applied to large-scale LLMs with extremely long sequences. First, head parallelism encounters scalability issues. In head parallelism, the degree of sequence parallelism inherently cannot exceed the number of attention heads. Therefore, there is an upper limit to the extent to which head parallelism can scale. Second, context parallelism encounters communication efficiency issues. Context parallelism employs point-to-point (P2P) communication primitives. However, P2P suffers from low intra-node bandwidth utilization and low inter-node network resource utilization. This bottleneck makes it difficult to overlap communication with computation when scaling the context parallelism dimension. | ||
| 6 | - | ||
| 7 | -## Solution | ||
| 8 | - | ||
| 9 | -The Double Ring Attention algorithm is supported, further accelerating the original Ring Attention implementation. For algorithm details, refer to [LoongTrain: Efficient Training of Long-Sequence LLMs with Head-Context Parallelism](<https://arxiv.org/pdf/2406.18485>). | ||
| 10 | - | ||
| 11 | -The original Ring Attention leverages the blockwise Softmax principle to perform blockwise attention computation without requiring the full matrix of the entire sequence. It performs self-attention and feedforward network computations in a blockwise manner, distributing the sequence dimension across multiple devices. Specifically, this method constructs a ring communication structure (Ring) for attention computation blocks among processes, where each process holds a sharded local QKV block. After computing the local attention, it traverses the process device ring by sending KV blocks backward and fetching KV blocks forward, performing attention and feedforward network computations block by block. Meanwhile, local attention computation and KV block communication can ideally overlap with each other, thereby eliminating the additionally introduced communication overhead. Furthermore, this approach requires no data concatenation throughout the entire attention computation process, and the supported sequence length can theoretically be extended infinitely. Building on this, the Double Ring Attention algorithm adopts a distributed attention mechanism, optimizing computation and memory usage through a dual-ring structure (Double Ring Attention). | ||
| 12 | - | ||
| 13 | -## Application Scenario | ||
| 14 | - | ||
| 15 | -Training scenarios where Ring Attention is already enabled. For how to enable Ring Attention, refer to [Ring Attention](ring-attention-context-parallel.md). | ||
| 16 | - | ||
| 17 | -## Usage | ||
| 18 | - | ||
| 19 | -In training scenarios where Ring Attention is enabled, set `--cp-window-size` to an integer greater than 1 to enable the Double Ring Attention algorithm and optimize the performance of the original Ring Attention. | ||
| 20 | - | ||
| 21 | -| Parameter | Description | Required (Yes/No) | Default Value | | ||
| 22 | -|------------------------|-----------------|---------|----------| | ||
| 23 | -| `--cp-window-size [int]` | Controls the inner window size of the two-level Ring Attention. When set to `1`, the original algorithm is used. When set to a value greater than `1`, the Double Ring Attention algorithm is used to optimize the performance of the original Ring Attention. Requires that `--context-parallel-size` be divisible by this parameter. | No | 1 | | ||
| 24 | - | ||
| 25 | -## Effects | ||
| 26 | - | ||
| 27 | -The input sequence is partitioned in parallel across multiple compute devices, and computational efficiency is improved through the dual-ring structure (Double Ring Attention). | ||
| 28 | - | ||
| 29 | -> [!NOTE] | ||
| 30 | -> | ||
| 31 | -> Ensure that `--context-parallel-size` is divisible by `--cp-window-size`. | ||
| 32 | -> Ensure that `--cp-window-size` is less than `--context-parallel-size`. | ||
| 33 | -> When the inner window `--cp-window-size` increases, the degree of concurrency between communication and computation becomes higher. However, due to potential on-chip memory bandwidth contention during concurrent computation and communication, overall efficiency may decrease. Debugging should be performed based on the actual scenario. For example, for a pruned Llama2 model with a 32k sequence length, when cp is 16 and no other parallel partitioning is used, actual measurements show optimal performance with an inner window size of 2. | ||
| @@ -2,17 +2,17 @@ | |||
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | -MoE models have long faced critical issues such as a high proportion of All2All communication overhead and large memory consumption. To better achieve All2All communication overlap, DeepSeek proposed DualPipe arrangement and MoE cross-microbatch forward and backward pass communication overlap. For details, see [DualPipe](https://github.com/deepseek-ai/DualPipe). | 5 | +MoE models have long faced critical issues such as a high proportion of All2All communication overhead and large memory consumption. To better achieve All2All communication overlap, DeepSeek proposed DualPipe arrangement and MoE cross-microbatch forward and backward pass communication overlap [1](https://github.com/deepseek-ai/DualPipe). |
| 6 | 6 | ||
| 7 | The DualPipe pipeline not only creates conditions for cross-microbatch computation and communication parallelism, achieving full All2All overlap in the stable stage, but also delivers better overall performance in terms of bubble ratio and activation memory during the warmup stage compared to traditional approaches. In both the warmup and cooldown stages, DualPipe adopts the dw separation concept from Zero Bubble to further reduce bubbles. At the same time, this pipeline arrangement has a natural affinity for the MTP model structure. Since the first and last stages reside on the same card, this pipeline also makes it easier to adjust the load balancing strategy across the PP dimension. The downside is that the required parameter count per card is doubled. | 7 | The DualPipe pipeline not only creates conditions for cross-microbatch computation and communication parallelism, achieving full All2All overlap in the stable stage, but also delivers better overall performance in terms of bubble ratio and activation memory during the warmup stage compared to traditional approaches. In both the warmup and cooldown stages, DualPipe adopts the dw separation concept from Zero Bubble to further reduce bubbles. At the same time, this pipeline arrangement has a natural affinity for the MTP model structure. Since the first and last stages reside on the same card, this pipeline also makes it easier to adjust the load balancing strategy across the PP dimension. The downside is that the required parameter count per card is doubled. |
| 8 | 8 | ||
| 9 | ## Solution | 9 | ## Solution |
| 10 | 10 | ||
| 11 | -Building upon DualPipe, an improved pipeline arrangement called [DualPipeV](https://zhuanlan.zhihu.com/p/26915547331) has been proposed. It takes half of DualPipe along the PP dimension in the pipeline, while further partitioning the model on top of the PP partitioning, resulting in a V-shaped pipeline arrangement. It addresses the issue of redundant parameters in DualPipe, and the algorithm's launch scale is only half that of DualPipe. | 11 | +Building upon DualPipe, an improved pipeline arrangement called DualPipeV has been proposed [2](https://zhuanlan.zhihu.com/p/26915547331). It takes half of DualPipe along the PP dimension in the pipeline, while further partitioning the model on top of the PP partitioning, resulting in a V-shaped pipeline arrangement. It addresses the issue of redundant parameters in DualPipe, and the algorithm's launch scale is only half that of DualPipe. |
| 12 | 12 | ||
| 13 | The following figure shows the DualPipeV pipeline arrangement using PP4 with 10 microbatches as an example. | 13 | The following figure shows the DualPipeV pipeline arrangement using PP4 with 10 microbatches as an example. |
| 14 |  | 14 |  |
| 15 | -In the figure, 0~9 and 10~19 represent the en microbatches of forward and backward stages on the same rank. The green sections represent the parallel forward and backward pass of different microbatches. After enabling cross-microbatch forward and backward pass communication overlap, both All2All communication and P2P communication can be overlapped by computations without dependencies. For a detailed introduction to this feature, see [MoE Cross-Microbatch Forward and Backward Overlap](megatron_moe/megatron-moe-fb-overlap.md). | 15 | +In the figure, 0~9 and 10~19 represent the two stages of the same microbatch on the same rank. The green sections represent the parallel forward and backward pass of different microbatches. After enabling cross-microbatch forward and backward pass communication overlap, both All2All communication and P2P communication can be overlapped by computations without dependencies. For a detailed introduction to this feature, see [MoE Cross-Microbatch Forward and Backward Overlap](megatron_moe/megatron-moe-fb-overlap.md). |
| 16 | 16 | ||
| 17 | During the warmup stage, MindSpeed achieves as much P2P communication overlap as possible. During the cooldown stage, in the DualPipeV implementation, the last PP card continuously computes PP_size backward stages. Before the corresponding dw computation is completed, the activations are not fully released, which can significantly increase the peak memory during the cooldown stage in certain recomputation or other memory-intensive scenarios. Therefore, in the MindSpeed implementation, dw separation during the cooldown stage is disabled by default, reducing the memory peak in recomputation scenarios at a small performance cost. A parameter option for dw separation is also provided. The pipeline when dw separation is enabled is shown in the following figure. | 17 | During the warmup stage, MindSpeed achieves as much P2P communication overlap as possible. During the cooldown stage, in the DualPipeV implementation, the last PP card continuously computes PP_size backward stages. Before the corresponding dw computation is completed, the activations are not fully released, which can significantly increase the peak memory during the cooldown stage in certain recomputation or other memory-intensive scenarios. Therefore, in the MindSpeed implementation, dw separation during the cooldown stage is disabled by default, reducing the memory peak in recomputation scenarios at a small performance cost. A parameter option for dw separation is also provided. The pipeline when dw separation is enabled is shown in the following figure. |
| 18 | . | 18 | . |
| @@ -46,23 +46,26 @@ The following table shows the bubble comparison across different pipeline arrang | |||
| 46 | 46 | ||
| 47 | ## Application Scenario | 47 | ## Application Scenario |
| 48 | 48 | ||
| 49 | +**Backend constraint:** When `--moe-fb-overlap` is enabled, you must set `--transformer-impl transformer_engine`. | ||
| 50 | + | ||
| 49 | In MoE scenarios, when All2All communication is too long and impacts performance, you can leverage the combined characteristics of DualPipeV and MoE cross-microbatch forward and backward pass communication overlap to improve performance. | 51 | In MoE scenarios, when All2All communication is too long and impacts performance, you can leverage the combined characteristics of DualPipeV and MoE cross-microbatch forward and backward pass communication overlap to improve performance. |
| 50 | 52 | ||
| 51 | ## Usage | 53 | ## Usage |
| 52 | 54 | ||
| 53 | -1. Add `--schedules-method dualpipev` to the launch script to enable the DualPipeV pipeline arrangement. | 55 | +Add `--schedules-method dualpipev --untie-embeddings-and-output-weights` to the launch script to enable the DualPipeV pipeline arrangement. |
| 54 | 56 | ||
| 55 | -2. Additionally add `--moe-fb-overlap` to the launch script to enable MoE cross-microbatch forward and backward communication overlap. | 57 | +Additionally add `--moe-fb-overlap` to the launch script to enable MoE cross-microbatch forward and backward pass communication overlap. |
| 56 | 58 | ||
| 57 | -3. Additionally add `--dualpipev-dw-detach` to the launch script to enable dw detachment in the cooldown stage. | 59 | +Additionally add `--dualpipev-dw-detach` to the launch script to enable dw detachment in the cooldown stage. |
| 58 | 60 | ||
| 59 | -4. When using DualPipeV, set the number of model layers to a multiple of `PP*2`. Also, the number of micro batches per PP group should be set to at least `PP*2`. It is incompatible with other pipeline features such as VPP. It is also currently incompatible with features such as long sequence parallelism, asynchronous DDP, swap-attention, and tp_2d. | 61 | +PP must be greater than 1, the number of model layers must be at least `2 * PP`, and the number of microbatches per PP group must be at least `2 * PP - 1`. |
| 60 | 62 | ||
| 61 | ## Effects | 63 | ## Effects |
| 62 | 64 | ||
| 63 | -- After enabling DualPipeV and MoE cross-microbatch forward and backward pass communication overlap, the All2All communication of MoE can be overlapped, achieving performance improvement. However, in certain scenarios (such as severe load imbalance in MoE), enabling DualPipeV may exacerbate PP load imbalance and cause performance degradation. Therefore, performance changes need to be analyzed on a scenario-by-scenario basis. | 65 | +After enabling DualPipeV and MoE cross-microbatch forward and backward pass communication overlap, the All2All communication of MoE can be overlapped, achieving performance improvement. However, in certain scenarios (such as severe load imbalance in MoE), enabling DualPipeV may exacerbate PP load imbalance and cause performance degradation. Therefore, performance changes need to be analyzed on a scenario-by-scenario basis. |
| 64 | -- Enabling DualPipeV may cause an increase in peak memory. The reason is that in DualPipeV, the output head is assigned to PP rank0, which leads to an increase in both static and dynamic memory. However, in certain scenarios (such as when the last N layers of the model are set as empty layers), since the tail stage is on PP rank0, the peak memory may decrease after enabling DualPipeV. Therefore, memory changes after enabling DualPipeV need to be analyzed on a case-by-case basis. | ||
| 65 | 66 | ||
| 66 | -> [!NOTE] | 67 | +Enabling DualPipeV may cause an increase in peak memory. The reason is that in DualPipeV, the output head is assigned to PP rank0, which leads to an increase in both static and dynamic memory. However, in certain scenarios (such as when the last N layers of the model are set as empty layers), since the tail stage is on PP rank0, the peak memory may decrease after enabling DualPipeV. Therefore, memory changes after enabling DualPipeV need to be analyzed on a case-by-case basis. |
| 67 | -> | 68 | + |
| 68 | -> Currently, `use_custom_fsdp` and `dualpipev` are incompatible. | 69 | +## Usage Constraints |
| 70 | + | ||
| 71 | +It is incompatible with FSDP, `--overlap-grad-reduce`, CP, VPP, or `--pipeline-model-parallel-layout`. | ||
| @@ -1,24 +1,46 @@ | |||
| 1 | # Support for the EOD Reset Training Scenario | 1 | # Support for the EOD Reset Training Scenario |
| 2 | 2 | ||
| 3 | -## Background and Challenges | 3 | +## EOD Reset Training Scenario |
| 4 | 4 | ||
| 5 | Typically, a text sequence fed into the model within a batch is formed by concatenating multiple documents. By default, these documents are treated as a single sequence, with no masking applied to the self attention between them. In certain cases, the documents are required to be independent, meaning they cannot perform self attention on each other. In this scenario, the attention mask and position ids need to be reset at the end of each document (EOD). When the `--reset-position-ids` parameter is disabled, position encoding is calculated for the entire sequence; when enabled, position encoding is calculated independently within each sequence. | 5 | Typically, a text sequence fed into the model within a batch is formed by concatenating multiple documents. By default, these documents are treated as a single sequence, with no masking applied to the self attention between them. In certain cases, the documents are required to be independent, meaning they cannot perform self attention on each other. In this scenario, the attention mask and position ids need to be reset at the end of each document (EOD). When the `--reset-position-ids` parameter is disabled, position encoding is calculated for the entire sequence; when enabled, position encoding is calculated independently within each sequence. |
| 6 | 6 | ||
| 7 | ## Solution | 7 | ## Solution |
| 8 | 8 | ||
| 9 | -The EOD Reset training scenario is supported by invoking the variable-length mode of the underlying flash-attention operator. Additionally, in the EOD Reset training scenario, Ring Attention parallelism for long sequences is supported to accelerate processing for ultra-long sequence scenarios. | 9 | +The EOD Reset training scenario is supported by invoking the variable-length mode of the underlying Flash Attention operator; it can be combined with Ring Attention or KVAllGather long sequence parallelism. |
| 10 | 10 | ||
| 11 | ## Usage | 11 | ## Usage |
| 12 | 12 | ||
| 13 | -1. Data Preparation | 13 | +**Backend restriction:** When CP>1, `--transformer-impl transformer_engine` must be set. |
| 14 | - - First, ensure that an EOD token is added to the end of each document. | ||
| 15 | - - When `--attention-mask-type` is set to `causal`, due to internal implementation requirements, the length of each subsequence will be padded online to a multiple of CP × lcm(2, TP), where lcm is the least common multiple. In this scenario, `--variable-seq-lengths` must be enabled because padding will cause the sequence length to change. | ||
| 16 | 14 | ||
| 17 | -2. Parameter Settings | 15 | +| Parallelism Method | Supported Mask Types | |
| 18 | - - Enable the `--reset-attention-mask` option. | 16 | +| --- | --- | |
| 19 | - - Use the `--reset-position-ids` option to indicate whether position encoding is reset. | 17 | +| CP=1 | causal, general | |
| 20 | - - `--attention-mask-type` can be specified as `causal` or `general`; both produce equivalent computation results. `causal` is an accelerated implementation, while `general` is the baseline approach. | 18 | +| Ring (p2p) | causal | |
| 19 | +| KVAllGather (all_gather / allgather) | causal | | ||
| 20 | +| Ulysses (a2a) | Not supported | | ||
| 21 | +| Hybrid CP (a2a+p2p) | Not supported | | ||
| 21 | 22 | ||
| 22 | -> [!NOTE] | 23 | +When CP>1, ensure that the CP communication type is consistent across layers. |
| 23 | -> | 24 | + |
| 24 | -> In the Ascend EOD Reset training scenario, when mask-type is set to general, Ring/Hybrid Attention performance drops significantly compared to Ulysses, which is expected behavior. When mask-type is set to `causal`, the accelerated implementation is used. | 25 | +### 1. Data Preparation |
| 26 | + | ||
| 27 | +(1) First, ensure that an EOD Token is added to the end of each document. | ||
| 28 | +(2) When using `p2p + causal` and CP>1, each subsequence is padded online to a multiple of `CP*lcm(2, TP)`, where lcm is the least common multiple. This per-document padding does not apply to CP=1 or KVAllGather. For EOD Reset with CP>1, `--variable-seq-lengths` must be enabled. | ||
| 29 | + | ||
| 30 | +### 2. Parameter Settings | ||
| 31 | + | ||
| 32 | +| Parameter | Support and Function | | ||
| 33 | +| --- | --- | | ||
| 34 | +| `--use-flash-attn` | Must be enabled when using `local`. | | ||
| 35 | +| `--reset-attention-mask` | Enables attention isolation between documents; for supported combinations, see the table above. | | ||
| 36 | +| `--reset-position-ids` | Can be enabled or disabled; when enabled, the position encoding of each document is recounted, and when disabled, it remains continuous. | | ||
| 37 | +| `--eod-mask-loss` | Optional; masks the loss at the position of the EOD token; DSA does not support this option. | | ||
| 38 | +| `--fix-sub-seq-length N` | Default is -1, which splits by EOD boundaries; when 0<N<=seq-length, a fixed subsequence length is used and the last segment retains the remainder; other values still split by EOD boundaries. | | ||
| 39 | +| `--variable-seq-lengths` | Must be set when CP>1; for CP=1, it is not mandatory for EOD Reset. | | ||
| 40 | + | ||
| 41 | +### 3. Notes | ||
| 42 | + | ||
| 43 | +- When CP or SP is enabled, `--micro-batch-size 1` must be set; when CP=1 and SP is not enabled, `--micro-batch-size` greater than 1 is supported. | ||
| 44 | +- When EOD Reset is combined with MoE, if `--variable-seq-lengths` is enabled, use the `alltoall` dispatcher; `allgather` does not support dynamic sequence lengths. | ||
| 45 | +- `--reset-attention-mask` disables RoPE fusion. | ||
| 46 | +- SFT packed sequence is not supported. | ||
| @@ -13,7 +13,7 @@ This document describes the features related to MindSpeed Core. | |||
| 13 | </thead> | 13 | </thead> |
| 14 | <tbody> | 14 | <tbody> |
| 15 | <tr> | 15 | <tr> |
| 16 | - <td rowspan="13">Megatron Features</td> | 16 | + <td rowspan="12">Megatron Features</td> |
| 17 | <td><a href="../features/data-parallel.md">Megatron Data Parallelism</a></td> | 17 | <td><a href="../features/data-parallel.md">Megatron Data Parallelism</a></td> |
| 18 | </tr> | 18 | </tr> |
| 19 | <tr> | 19 | <tr> |
| @@ -40,9 +40,6 @@ This document describes the features related to MindSpeed Core. | |||
| 40 | <tr> | 40 | <tr> |
| 41 | <td><a href="../features/recomputation.md">Megatron Recomputation</a></td> | 41 | <td><a href="../features/recomputation.md">Megatron Recomputation</a></td> |
| 42 | </tr> | 42 | </tr> |
| 43 | - <tr> | ||
| 44 | - <td><a href="../features/dist_ckpt.md">Megatron Distributed Weight</a></td> | ||
| 45 | - </tr> | ||
| 46 | <tr> | 43 | <tr> |
| 47 | <td><a href="../features/custom_fsdp.md">Megatron Fully Sharded Data Parallelism</a></td> | 44 | <td><a href="../features/custom_fsdp.md">Megatron Fully Sharded Data Parallelism</a></td> |
| 48 | </tr> | 45 | </tr> |
| @@ -59,12 +56,6 @@ This document describes the features related to MindSpeed Core. | |||
| 59 | <tr> | 56 | <tr> |
| 60 | <td><a href="../features/ring-attention-context-parallel.md">Ascend Ring Attention Long-Sequence Parallelism</a></td> | 57 | <td><a href="../features/ring-attention-context-parallel.md">Ascend Ring Attention Long-Sequence Parallelism</a></td> |
| 61 | </tr> | 58 | </tr> |
| 62 | - <tr> | ||
| 63 | - <td><a href="../features/double-ring.md">Ascend Double Ring Attention Long-Sequence Parallelism</a></td> | ||
| 64 | - </tr> | ||
| 65 | - <tr> | ||
| 66 | - <td><a href="../features/hybrid-context-parallel.md">Ascend Hybrid Long-Sequence Parallelism</a></td> | ||
| 67 | - </tr> | ||
| 68 | <tr> | 59 | <tr> |
| 69 | <td><a href="../features/noop-layers.md">Ascend Custom No-Op Layer</a></td> | 60 | <td><a href="../features/noop-layers.md">Ascend Custom No-Op Layer</a></td> |
| 70 | </tr> | 61 | </tr> |
| @@ -72,11 +63,14 @@ This document describes the features related to MindSpeed Core. | |||
| 72 | <td><a href="../features/dualpipev.md">Ascend DualPipeV</a></td> | 63 | <td><a href="../features/dualpipev.md">Ascend DualPipeV</a></td> |
| 73 | </tr> | 64 | </tr> |
| 74 | <tr> | 65 | <tr> |
| 75 | - <td rowspan="9">Memory Optimization</td> | 66 | + <td><a href="../features/kvallgather-context-parallel.md">KVAllGather Long-Sequence Parallelism</a></td> |
| 76 | - <td><a href="../features/activation-function-recompute.md">Ascend Activation Function Recomputation</a></td> | ||
| 77 | </tr> | 67 | </tr> |
| 78 | <tr> | 68 | <tr> |
| 79 | - <td><a href="../features/recompute_independent_pipelining.md">Ascend Independent Pipelining of Recomputation</a></td> | 69 | + <td><a href="../features/pipeline-model-parallel-layout.md">Megatron Custom Pipeline Layout</a></td> |
| 70 | + </tr> | ||
| 71 | + <tr> | ||
| 72 | + <td rowspan="10">Memory Optimization</td> | ||
| 73 | + <td><a href="../features/activation-function-recompute.md">Ascend Activation Function Recomputation</a></td> | ||
| 80 | </tr> | 74 | </tr> |
| 81 | <tr> | 75 | <tr> |
| 82 | <td><a href="../features/generate-mask.md">Ascend Mask Generation</a></td> | 76 | <td><a href="../features/generate-mask.md">Ascend Mask Generation</a></td> |
| @@ -100,18 +94,51 @@ This document describes the features related to MindSpeed Core. | |||
| 100 | <td><a href="../features/virtual-optimizer.md">Virtual Optimizer</a></td> | 94 | <td><a href="../features/virtual-optimizer.md">Virtual Optimizer</a></td> |
| 101 | </tr> | 95 | </tr> |
| 102 | <tr> | 96 | <tr> |
| 103 | - <td>Affinity Computation</td> | 97 | + <td><a href="../features/param-and-grad-buffer-pad.md">Parameter and Gradient Buffer Alignment</a></td> |
| 98 | + </tr> | ||
| 99 | + <tr> | ||
| 100 | + <td><a href="../features/swap-layer-input.md">Transformer Layer Input Offloading</a></td> | ||
| 101 | + </tr> | ||
| 102 | + <tr> | ||
| 103 | + <td rowspan="10">Affinity Computation</td> | ||
| 104 | + <td><a href="../features/rms_norm.md">Ascend rms_norm Fusion Operator</a></td> | ||
| 105 | + </tr> | ||
| 106 | + <tr> | ||
| 107 | + <td><a href="../features/swiglu.md">Ascend swiglu Fusion Operator</a></td> | ||
| 108 | + </tr> | ||
| 109 | + <tr> | ||
| 110 | + <td><a href="../features/rotary-embedding.md">Ascend rotary_embedding Fusion Operator</a></td> | ||
| 111 | + </tr> | ||
| 112 | + <tr> | ||
| 104 | <td><a href="../features/flash-attention.md">Ascend Flash Attention</a></td> | 113 | <td><a href="../features/flash-attention.md">Ascend Flash Attention</a></td> |
| 105 | </tr> | 114 | </tr> |
| 115 | + <tr> | ||
| 116 | + <td><a href="../features/moe-token-permute-and-unpermute.md">Ascend Moe Token Permute and Unpermute Fusion Operator</a></td> | ||
| 117 | + </tr> | ||
| 118 | + <tr> | ||
| 119 | + <td><a href="../features/npu_matmul_add.md">Ascend npu_matmul_add_fp32 Gradient Accumulation Fusion Operator</a></td> | ||
| 120 | + </tr> | ||
| 121 | + <tr> | ||
| 122 | + <td><a href="../features/communication-over-computation.md">Ascend Communication Over Computation</a></td> | ||
| 123 | + </tr> | ||
| 124 | + <tr> | ||
| 125 | + <td><a href="../features/mc2.md">Ascend MC2</a></td> | ||
| 126 | + </tr> | ||
| 127 | + <tr> | ||
| 128 | + <td><a href="../features/hif8_dts.md">HiF8 DTS (Delayed Tensor Scaling) Training</a></td> | ||
| 129 | + </tr> | ||
| 130 | + <tr> | ||
| 131 | + <td><a href="../features/te-comparsion-online.md">Low-Precision Online Comparison</a></td> | ||
| 132 | + </tr> | ||
| 106 | <tr> | 133 | <tr> |
| 107 | <td rowspan="2">Communication Optimization</td> | 134 | <td rowspan="2">Communication Optimization</td> |
| 108 | <td><a href="../features/hccl-replace-gloo.md">Ascend Gloo Snapshot Persistence Optimization</a></td> | 135 | <td><a href="../features/hccl-replace-gloo.md">Ascend Gloo Snapshot Persistence Optimization</a></td> |
| 109 | </tr> | 136 | </tr> |
| 110 | <tr> | 137 | <tr> |
| 111 | - <td><a href="../features/tensor-parallel-2d.md">Ascend High-Dimensional Tensor Parallelism</a></td> | 138 | + <td><a href="../features/async-log-allreduce.md">Async Log Allreduce</a></td> |
| 112 | </tr> | 139 | </tr> |
| 113 | <tr> | 140 | <tr> |
| 114 | - <td rowspan="8">Mcore MoE Features</td> | 141 | + <td rowspan="9">Mcore MoE Features</td> |
| 115 | <td><a href="../features/megatron_moe/megatron-moe-gmm.md">Ascend Megatron MoE GMM</a></td> | 142 | <td><a href="../features/megatron_moe/megatron-moe-gmm.md">Ascend Megatron MoE GMM</a></td> |
| 116 | </tr> | 143 | </tr> |
| 117 | <tr> | 144 | <tr> |
| @@ -121,7 +148,7 @@ This document describes the features related to MindSpeed Core. | |||
| 121 | <td><a href="../features/megatron_moe/megatron-moe-alltoall-dispatcher.md">Ascend Megatron MoE Alltoall Dispatcher Performance Optimization</a></td> | 148 | <td><a href="../features/megatron_moe/megatron-moe-alltoall-dispatcher.md">Ascend Megatron MoE Alltoall Dispatcher Performance Optimization</a></td> |
| 122 | </tr> | 149 | </tr> |
| 123 | <tr> | 150 | <tr> |
| 124 | - <td><a href="../features/megatron_moe/megatron-moe-tp-extend-ep.md">Ascend Megatron MoE TP Extended EP</a></td> | 151 | + <td><a href="../features/megatron_moe/megatron-moe-alltoall-overlap-comm.md">Communication Overlap for Megatron MoE AlltoAll Dispatcher</a></td> |
| 125 | </tr> | 152 | </tr> |
| 126 | <tr> | 153 | <tr> |
| 127 | <td><a href="../features/megatron_moe/megatron-moe-allgather-overlap-comm.md">Communication Overlap for Megatron MoE AlltoAll Dispatcher</a></td> | 154 | <td><a href="../features/megatron_moe/megatron-moe-allgather-overlap-comm.md">Communication Overlap for Megatron MoE AlltoAll Dispatcher</a></td> |
| @@ -133,31 +160,45 @@ This document describes the features related to MindSpeed Core. | |||
| 133 | <td><a href="../features/megatron_moe/megatron-moe-fb-overlap.md">1F1B Overlap</a></td> | 160 | <td><a href="../features/megatron_moe/megatron-moe-fb-overlap.md">1F1B Overlap</a></td> |
| 134 | </tr> | 161 | </tr> |
| 135 | <tr> | 162 | <tr> |
| 136 | - <td><a href="../features/balanced_moe.md">Dynamically Balanced Expert Parallelism (Data-Parameter Mutual Search)</a></td> | 163 | + <td><a href="../features/megatron_moe/megatron-moe-zero-memory.md">Megatron MoE Alltoall Dispatcher Memory Optimization</a></td> |
| 137 | </tr> | 164 | </tr> |
| 138 | <tr> | 165 | <tr> |
| 139 | - <td>Key Scenario</td> | 166 | + <td><a href="../features/megatron_moe/megatron-moe-fix-router.md">MoE Fixed Routing</a></td> |
| 167 | + </tr> | ||
| 168 | + <tr> | ||
| 169 | + <td rowspan="4">Key Scenario</td> | ||
| 140 | <td><a href="../features/eod-reset.md">Ascend EOD Reset Training</a></td> | 170 | <td><a href="../features/eod-reset.md">Ascend EOD Reset Training</a></td> |
| 141 | </tr> | 171 | </tr> |
| 142 | <tr> | 172 | <tr> |
| 143 | - <td rowspan="5">Multimodal Features</td> | 173 | + <td><a href="../features/deepseek-sparse-attention.md">DeepSeek Sparse Attention (DSA)</a></td> |
| 144 | - <td><a href="../features/variable_seq_lengths.md">PP Support for Variable Sequence Lengths</a></td> | ||
| 145 | </tr> | 174 | </tr> |
| 146 | <tr> | 175 | <tr> |
| 147 | - <td><a href="../features/multi_parameter_pipeline.md">Ascend Multi-Parameter Pipeline</a></td> | 176 | + <td><a href="../features/gated-delta-net.md">GatedDeltaNet (GDN)</a></td> |
| 148 | </tr> | 177 | </tr> |
| 149 | <tr> | 178 | <tr> |
| 150 | - <td><a href="../features/multi_parameter_pipeline_and_variable_seq_lengths.md">Ascend Multi-Parameter Pipeline and Variable Sequence Lengths</a></td> | 179 | + <td><a href="../features/preprocess-eod-data.md">Pack Mode Pre-training Dataset Processing</a></td> |
| 151 | </tr> | 180 | </tr> |
| 152 | <tr> | 181 | <tr> |
| 153 | - <td><a href="../features/unaligned_linear.md">Ascend Unaligned Linear Layer</a></td> | 182 | + <td rowspan="7">Others</td> |
| 154 | - </tr> | ||
| 155 | - <tr> | ||
| 156 | - <td><a href="../features/unaligned-ulysses-context-parallel.md">Ascend Unaligned Ulysses Long-Sequence Parallelism</a></td> | ||
| 157 | - </tr> | ||
| 158 | - <tr> | ||
| 159 | - <td>Others</td> | ||
| 160 | <td><a href="../features/ops_flops_cal.md">Ascend TFLOPS Calculation</a></td> | 183 | <td><a href="../features/ops_flops_cal.md">Ascend TFLOPS Calculation</a></td> |
| 161 | </tr> | 184 | </tr> |
| 185 | + <tr> | ||
| 186 | + <td><a href="../features/npu_deterministic.md">Ascend Deterministic Computing</a></td> | ||
| 187 | + </tr> | ||
| 188 | + <tr> | ||
| 189 | + <td><a href="../features/npu_datadump.md">Ascend MindStudio Training Tools for Precision Comparison</a></td> | ||
| 190 | + </tr> | ||
| 191 | + <tr> | ||
| 192 | + <td><a href="../features/muon-optimizer.md">Muon Optimizer</a></td> | ||
| 193 | + </tr> | ||
| 194 | + <tr> | ||
| 195 | + <td><a href="../features/aiqos.md">AI QoS Differentiated Scheduling</a></td> | ||
| 196 | + </tr> | ||
| 197 | + <tr> | ||
| 198 | + <td><a href="../features/cache-get-batch-config.md">get_batch Config Cache</a></td> | ||
| 199 | + </tr> | ||
| 200 | + <tr> | ||
| 201 | + <td><a href="../features/pretrained-from-hf-tokenizer.md">PretrainedFromHF Tokenizer</a></td> | ||
| 202 | + </tr> | ||
| 162 | </tbody> | 203 | </tbody> |
| 163 | </table> | 204 | </table> |
| @@ -1,4 +1,4 @@ | |||
| 1 | -# Flash Attention | 1 | +# Flash attention |
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| @@ -8,27 +8,28 @@ In the field of deep learning, Transformer models are widely used in various dom | |||
| 8 | 8 | ||
| 9 | To overcome the above challenges, Flash Attention technology was introduced. Flash Attention is an efficient attention mechanism designed to significantly reduce the computation time and memory overhead of Transformer models when processing long sequences while maintaining model performance. The key to accelerating attention lies in optimizing IO memory access, i.e., reducing the number of read/write operations on on-chip memory. | 9 | To overcome the above challenges, Flash Attention technology was introduced. Flash Attention is an efficient attention mechanism designed to significantly reduce the computation time and memory overhead of Transformer models when processing long sequences while maintaining model performance. The key to accelerating attention lies in optimizing IO memory access, i.e., reducing the number of read/write operations on on-chip memory. |
| 10 | 10 | ||
| 11 | -Flash Attention is an exact attention method that optimizes IO memory access overhead. Its principle is shown in Figure 1. It reduces the number of memory reads/writes between high-bandwidth memory (on-chip memory) and SRAM through techniques such as Tiling, recomputation, and Kernel Fusion. | 11 | +Flash Attention is an exact attention method that optimizes IO memory access overhead. Its principle is shown in Figure 1. It reduces the number of memory reads/writes between high-bandwidth memory (on-chip memory) and SRAM through techniques such as Tiling, recomputation, and Kernel Fusion. The NPU side provides the same solution. For the detailed interface and usage instructions of this fusion operator, see the fusion_attention interface in the fusion operator API list. |
| 12 | 12 | ||
| 13 | * Tiling: Uses faster SRAM instead of on-chip memory. However, SRAM has limited memory capacity and cannot complete the full attention computation for all data at once, so block-wise computation is required. | 13 | * Tiling: Uses faster SRAM instead of on-chip memory. However, SRAM has limited memory capacity and cannot complete the full attention computation for all data at once, so block-wise computation is required. |
| 14 | * Recomputation: Discards intermediate results from being written back and recomputes them when needed, trading computation for memory access. | 14 | * Recomputation: Discards intermediate results from being written back and recomputes them when needed, trading computation for memory access. |
| 15 | * Kernel fusion: Fuses multiple operations into a single operation, using one kernel to complete the entire computation based on Tiling. | 15 | * Kernel fusion: Fuses multiple operations into a single operation, using one kernel to complete the entire computation based on Tiling. |
| 16 | 16 | ||
| 17 | -<p align="left"> <img src="../figures/flash_attention.png" height="280px" width="850px"></p> | 17 | +<p align="center"> <img src="../figures/flash_attention.png" height="280px" width="850px"></p> |
| 18 | 18 | ||
| 19 | For more information about Flash Attention, see [FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://arxiv.org/pdf/2205.14135). | 19 | For more information about Flash Attention, see [FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://arxiv.org/pdf/2205.14135). |
| 20 | 20 | ||
| 21 | ## Application Scenario | 21 | ## Application Scenario |
| 22 | 22 | ||
| 23 | +**Backend limitation:** When CP>1, `--transformer-impl transformer_engine` must be set. | ||
| 24 | + | ||
| 23 | This method is applicable to self-attention related models, especially for long sequence input scenarios. This feature is enabled by default when long sequence parallelism is turned on. | 25 | This method is applicable to self-attention related models, especially for long sequence input scenarios. This feature is enabled by default when long sequence parallelism is turned on. |
| 24 | 26 | ||
| 25 | ## Usage | 27 | ## Usage |
| 26 | 28 | ||
| 27 | Set the following parameter to call this algorithm: | 29 | Set the following parameter to call this algorithm: |
| 30 | +`--use-flash-attn` | ||
| 28 | 31 | ||
| 29 | -```bash | 32 | +The `--sparse-mode` launch parameter only supports `0` (default) and `2` (top-left causal compression). For the mask support scope in different CP and EOD scenarios, see [Mask Generation](generate-mask.md#application-scenario). |
| 30 | ---use-flash-attn | ||
| 31 | -``` | ||
| 32 | 33 | ||
| 33 | ## Effects | 34 | ## Effects |
| 34 | 35 | ||
| @@ -1,65 +0,0 @@ | |||
| 1 | -# FSDP2 | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -PyTorch's Fully Sharded Data Parallel (FSDP) aims to provide a high-performance eager-mode implementation with communication bucketing and communication/computation overlap. The API represents communication buckets by flattening and concatenating a group of parameters into a FlatParameter. However, this FlatParameter design makes it difficult to apply differentiated operations (such as parameter freezing and precision conversion) to individual parameters within a bucket, compromising composability. It also complicates the internal implementation—for example, the state dict logic spans thousands of lines of code and requires additional communication. | ||
| 6 | - | ||
| 7 | -## Solution | ||
| 8 | - | ||
| 9 | -To address these limitations, FSDP2 removes FlatParameter and uses DTensors sharded along dimension 0 to represent sharded parameters. This enables convenient operations on individual parameters, a communication-free sharded state dict, and a simplified initialization flow. | ||
| 10 | - | ||
| 11 | -## Usage | ||
| 12 | - | ||
| 13 | -In MindSpeed, the entry point for FSDP2 is a configuration file. By generating the configuration file and passing command-line arguments, you can use this feature. | ||
| 14 | - | ||
| 15 | -```bash | ||
| 16 | -export CUDA_DEVICE_MAX_CONNECTIONS=2 # Must not be set to 1 | ||
| 17 | ---use-torch-fsdp2 \ | ||
| 18 | ---fsdp2-config-path ./fsdp2_config.yaml \ | ||
| 19 | ---ckpt-format torch_dist \ | ||
| 20 | ---untie-embeddings-and-output-weights \ | ||
| 21 | -# Note: The distributed optimizer must not be enabled | ||
| 22 | -``` | ||
| 23 | - | ||
| 24 | -The configuration items for `fsdp2_config.yaml` are as follows: | ||
| 25 | - | ||
| 26 | -```yaml | ||
| 27 | -sharding_size: int # Sharding group size, indicating the number of NPUs in each parameter sharding group | ||
| 28 | -sub_modules_to_wrap: Optional[Iterable[torch.nn.Module]] = None # List of module classes to be wrapped by FSDP, must be imported via absolute path, e.g.: mindspeed_mm.models.predictor.dits.sat_dit.VideoDiTBlock | ||
| 29 | -reshard_after_forward: Union[bool, int] = True # Reshard parameters immediately after forward computation | ||
| 30 | -param_dtype: bf16 # Parameter storage precision | ||
| 31 | -reduce_dtype: fp32 # Gradient communication precision | ||
| 32 | -cast_forward_inputs: bool = True # Automatically cast forward inputs to compute precision | ||
| 33 | -ignored_modules: Optional[Iterable[torch.nn.Module]] = None # List of module classes to exclude from FSDP management, must be imported via absolute path: e.g., mindspeed_mm.models.ae.base.AEModel | ||
| 34 | -offload_to_cpu: bool = False # Offload weights, gradients, and optimizer states to CPU | ||
| 35 | -pin_memory: bool = True # Takes effect only when offload_to_cpu is True | ||
| 36 | -num_to_forward_prefetch: int # Specifies the number of layers for forward prefetch, default value is 0 | ||
| 37 | -recompute_modules: Optional[Iterable[torch.nn.Module]] = None # List of module classes that require recomputation, must be imported via absolute path, for example: mindspeed_mm.models.predictor.dits.sat_dit.VideoDiTBlock | ||
| 38 | -``` | ||
| 39 | - | ||
| 40 | -> [!NOTE] | ||
| 41 | -> | ||
| 42 | -> **Recomputation Mechanism Description**: In FSDP2 mode, the `recompute_modules` configuration item in `fsdp2_config.yaml` is used for recomputation, implemented based on PyTorch's native `apply_activation_checkpointing` + `checkpoint_wrapper`. It wraps specified modules with activation checkpointing, meaning intermediate activation values are not saved during forward propagation and are recomputed during backward propagation. | ||
| 43 | -> Recomputation in this mode is mutually exclusive with Megatron-style recompute (such as `--recompute-granularity`, `--recompute-method`, `--recompute-num-layers`) and cannot be enabled simultaneously. | ||
| 44 | -> | ||
| 45 | -> **Recomputation Performance Cost**: Recomputation trades computation for memory. Full-layer recomputation can save approximately 30–40% of memory, but may result in a 15–25% throughput drop. Partial recomputation can save approximately 15–25% of memory, with a throughput drop of about 5–10%. The actual cost depends on the model architecture, batch size, and hardware configuration. | ||
| 46 | -> | ||
| 47 | -> **Reasons for Throughput Drop**: Recomputation avoids saving intermediate activations during forward propagation and recomputes them during backward propagation, adding extra computational overhead. Additionally, if `reshard_after_forward=True` is configured, backward propagation also requires re-fetching sharded parameters, which may introduce additional communication overhead. | ||
| 48 | -> | ||
| 49 | -> **Recomputation Usage Boundary**: It is recommended to enable recompute only when activation memory is the primary bottleneck. Recommended conditions for enabling: OOM errors occur during training; activation memory usage exceeds 50% of total memory; or when a larger batch size or longer sequence length is desired. Not recommended when computation itself is the bottleneck (NPU utilization close to 100%), communication is the bottleneck (network bandwidth is saturated), or when the model is small, batch size is small, and memory is sufficient. | ||
| 50 | - | ||
| 51 | -## Effects | ||
| 52 | - | ||
| 53 | -For Llama-7b, FSDP2 achieves higher MFU compared to FSDP1, reduces peak memory by 7%, and maintains the same loss curve. | ||
| 54 | - | ||
| 55 | -## Notes | ||
| 56 | - | ||
| 57 | -1. When FSDP2 training is enabled, the distributed optimizer and its related configurations must be disabled. | ||
| 58 | - | ||
| 59 | -2. When FSDP2 training is enabled, the model weight save format `ckpt-format` only supports `torch_dist` or `torch_dcp`. | ||
| 60 | - | ||
| 61 | - - When configured as `torch_dist`, the model must implement the `sharded_state_dict()` method by inheriting from `MegatronModule` or through custom implementation; additionally, the 0-dimension size of all weights in the model must be greater than or equal to sharding_size. | ||
| 62 | - | ||
| 63 | - - When configured as `torch_dcp`, the model must implement the `state_dict_for_save_checkpoint()` method by inheriting from `MegatronModule` or through custom implementation, and the weight dictionary returned by this method must be consistent with the return value of `model.state_dict()`. | ||
| 64 | - | ||
| 65 | -3. When FSDP2 training is enabled, recomputation-related configurations must be disabled, including `--recompute-granularity`, `--recompute-method`, and `--recompute-num-layers`. | ||
| @@ -10,7 +10,7 @@ During training, the fused_ema_adamw optimizer maintains an `ema_params` state f | |||
| 10 | 10 | ||
| 11 | ema_params = ema_decay * ema_params + (1 - ema_decay) * model_params | 11 | ema_params = ema_decay * ema_params + (1 - ema_decay) * model_params |
| 12 | 12 | ||
| 13 | -```model_params``` represents the model parameters, and `ema_decay` is a hyperparameter. The `--ema-decay` can be specified in the training script using `--ema-decay <value>`. If not specified in the script, the default `ema_decay` is `0.9999`.<br> | 13 | +`model_params` represents the model parameters, and `ema_decay` is a hyperparameter. The `--ema-decay` can be specified in the training script using `--ema-decay <value>`. If not specified in the script, the default `ema_decay` is `0.9999`.<br> |
| 14 | 14 | ||
| 15 | ## Application Scenario | 15 | ## Application Scenario |
| 16 | 16 | ||
| @@ -24,7 +24,7 @@ Primarily used in multimodal training scenarios where the EMA model needs to be | |||
| 24 | ## Effects | 24 | ## Effects |
| 25 | 25 | ||
| 26 | 1. Since the fused_ema_adamw optimizer needs to maintain an additional `ema_params` state during training, memory overhead will increase.<br> | 26 | 1. Since the fused_ema_adamw optimizer needs to maintain an additional `ema_params` state during training, memory overhead will increase.<br> |
| 27 | -2. When saving weights, the optimizer's `ema_params` state will be stored in the `distrib_optim.pt` file.<br> | 27 | +2. When saving weights, the `ema_params` state will be stored in the `distrib_optim.pt` file.<br> |
| 28 | 3. When saving weights, the EMA model weight data will be stored in the `ema_model` field within the `model_optim_rng.pt` file.<br> | 28 | 3. When saving weights, the EMA model weight data will be stored in the `ema_model` field within the `model_optim_rng.pt` file.<br> |
| 29 | 29 | ||
| 30 | ## Notes | 30 | ## Notes |
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## Application Scenario | 3 | ## Application Scenario |
| 4 | 4 | ||
| 5 | -This method is the V2 version of FlashAttention, which extends certain functionalities beyond the V1 version. It currently only supports specific scenarios such as [ALiBi position encoding](./alibi.md) and is disabled by default. | 5 | +This method is the V2 version of Flash Attention, which extends certain functionalities beyond the V1 version. It currently only supports specific scenarios such as [ALiBi position encoding](./alibi.md) and is disabled by default. |
| 6 | 6 | ||
| 7 | For other scenarios, it is essentially identical to the V1 version, and it is not recommended to enable it proactively. For operator details, see [API Description](../ops/fusion_attention.md). | 7 | For other scenarios, it is essentially identical to the V1 version, and it is not recommended to enable it proactively. For operator details, see [API Description](../ops/fusion_attention.md). |
| 8 | 8 | ||
| @@ -12,4 +12,4 @@ Set `--use-fusion-attn-v2` to invoke this algorithm. | |||
| 12 | 12 | ||
| 13 | ## Effects | 13 | ## Effects |
| 14 | 14 | ||
| 15 | -The basic effect is equivalent to FlashAttention. For specific scenarios such as [ALiBi Positional Encoding](./alibi.md), it must be manually enabled. | 15 | +The basic effect is equivalent to Flash Attention. For specific scenarios such as [ALiBi Positional Encoding](./alibi.md), it must be manually enabled. |
| @@ -0,0 +1,13 @@ | |||
| 1 | +# GatedDeltaNet (GDN) | ||
| 2 | + | ||
| 3 | +Based on the GatedDeltaNet in Megatron-Core, MindSpeed provides NPU implementations of `chunk_gated_delta_rule` and `l2norm`, and the causal convolution uses the basic adaptation of MA. The non-deterministic mode uses MindSpeed's Triton gated delta rule. | ||
| 4 | + | ||
| 5 | +## Usage | ||
| 6 | + | ||
| 7 | +**Backend restriction:** GDN/hybrid models must set `--transformer-impl transformer_engine`, and `local` is not supported. | ||
| 8 | + | ||
| 9 | +Prepare the supporting environment according to [Software Installation](../user-guide/install_guide.md) and import `megatron_adaptor`. Set `--transformer-impl transformer_engine`. The model uses Megatron's native `--hybrid-layer-pattern` to describe the layer structure, where `G` represents a GDN layer; for example, `G*` represents one GDN layer and one Attention layer. The specific dimensions and layer arrangement follow the model configuration. | ||
| 10 | + | ||
| 11 | +When using a hybrid model pipeline, the stages are divided by `|` in `--hybrid-layer-pattern`, and it must not be configured together with `--pipeline-model-parallel-layout`, `--num-layers-per-virtual-pipeline-stage`, or `--num-virtual-stages-per-pipeline-rank`. | ||
| 12 | + | ||
| 13 | +This document describes the training path; GDN does not yet support the inference path. | ||
| @@ -2,58 +2,67 @@ | |||
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | -**Megatron Source Code Analysis** | 5 | +### 1. Megatron Source Code Analysis |
| 6 | 6 | ||
| 7 | -- Each device retrieves various data, including AttnMask, through `pretrain_gpt.py#L93`-`def get_batch`. | 7 | +[1] Each device retrieves various data, including AttnMask, through `pretrain_gpt.py`-`def get_batch`. |
| 8 | 8 | ||
| 9 | -- The first and last stages of PP retrieve various data, including AttnMask, through `megatron/training/utils.py#L276`-`def get_batch_on_this_tp_rank`. Other stages directly return None. | 9 | +[2] The first and last stages of PP retrieve various data, including AttnMask, through `megatron/core/utils.py`-`def get_batch_on_this_tp_rank`. Other stages directly return None. |
| 10 | 10 | ||
| 11 | -- The first TP node generates the AttnMask via `megatron/core/datasets/gpt_dataset.py#L675`-`def _get_ltor_masks_and_position_ids`. | 11 | +[3] The first TP node generates the AttnMask via `megatron/core/datasets/gpt_dataset.py`-`def _get_ltor_masks_and_position_ids`. |
| 12 | 12 | ||
| 13 | -- Other TP nodes directly generate an empty matrix with the same shape as the first node, and obtain the AttnMask generated by the first node through broadcast. | 13 | +[4] Other TP nodes directly generate an empty matrix with the same shape as the first node, and obtain the AttnMask generated by the first node through broadcast. |
| 14 | 14 | ||
| 15 | Tips: The above operations are enabled by default, and all generated AttnMasks are in the lower triangular shape. This can be disabled via `--no-create-attention-mask-in-dataloader`. | 15 | Tips: The above operations are enabled by default, and all generated AttnMasks are in the lower triangular shape. This can be disabled via `--no-create-attention-mask-in-dataloader`. |
| 16 | 16 | ||
| 17 | -**Problem Detection** | 17 | +### 2. Problem Detection |
| 18 | 18 | ||
| 19 | -- Ascend's FA requires an externally generated AttnMask, so in addition to the basic lower triangular mode, an additional interface is needed to generate custom AttnMasks. | 19 | +[1] Ascend's FA requires an externally generated AttnMask, so in addition to the basic lower triangular mode, an additional interface is needed to generate custom AttnMasks. |
| 20 | 20 | ||
| 21 | -- The AttnMask of non-PP head and tail nodes is `Non`e, which prevents FA acceleration from being enabled. | 21 | +[2] The AttnMask of non-PP head and tail nodes is `Non`e, which prevents FA acceleration from being enabled. |
| 22 | 22 | ||
| 23 | -- The generation, copying, and broadcasting of AttnMask are repeated with `get_batch` at each `micro_step`. | 23 | +[3] The generation, copying, and broadcasting of AttnMask are repeated with `get_batch` at each `micro_step`. |
| 24 | 24 | ||
| 25 | -- For long sequences, the generated AttnMask occupies excessive memory. | 25 | +[4] For long sequences, the generated AttnMask occupies excessive memory. |
| 26 | 26 | ||
| 27 | ## Solution | 27 | ## Solution |
| 28 | 28 | ||
| 29 | -- Provide a unified AttnMask generation API, where the same process reuses a global variable AttnMask to avoid repeated generation and copying. | 29 | +### Solution Approach |
| 30 | 30 | ||
| 31 | -- Adapt the AttnMask compression mode to reduce memory usage. | 31 | +[1] Provide a unified AttnMask generation API, where the same process reuses a global variable AttnMask to avoid repeated generation and copying. |
| 32 | + | ||
| 33 | +[2] Adapt the AttnMask compression mode to reduce memory usage. | ||
| 32 | 34 | ||
| 33 | ## Application Scenario | 35 | ## Application Scenario |
| 34 | 36 | ||
| 35 | -- Currently, mask generation for both FA and non-FA is supported, and the passed AttnMask can be none or in lower triangular mode. | 37 | +**Backend limitation:** The mask caching interface described in this document is only intended for `--transformer-impl local`. |
| 36 | 38 | ||
| 37 | -- In FA scenarios, when the sequence length is greater than 2048 or `ring_cp_algo` is used, the compression mode is adopted by default. | 39 | +| Configuration | Supported Scope | |
| 40 | +| --- | --- | | ||
| 41 | +| `--attention-mask-type causal` | Default value, causal attention; supports Ring, Ulysses, KVAllGather, and hybrid CP. | | ||
| 42 | +| `--attention-mask-type general` | General training supports Ring, Ulysses, and hybrid CP. EOD Reset is available only when CP=1. | | ||
| 43 | +| `--use-flash-attn --sparse-mode 0` | Default mode, computed based on the passed-in mask. | | ||
| 44 | +| `--use-flash-attn --sparse-mode 2` | A causal compressed mask aligned to the upper left. | | ||
| 38 | 45 | ||
| 39 | -- Other scenarios use the full mask. | 46 | +When CP>1, `--transformer-impl transformer_engine` is required. When combined with EOD Reset, only `p2p/all_gather + causal` is supported. For specific constraints, see [EOD Reset](eod-reset.md). `attention-mask-type` and `sparse-mode` are different parameters, and the operator mode used internally by TENPU is not equivalent to the selectable range of the startup parameters. |
| 47 | + | ||
| 48 | +The local DotProductAttention path generates and caches the mask when the mode is causal and the passed-in mask is None; FA generates a compressed mask of [2048,2048] by default, and the `multi_head_latent_attention` configuration uses the full sequence length. Non-FA uses the full mask. | ||
| 40 | 49 | ||
| 41 | ## Usage | 50 | ## Usage |
| 42 | 51 | ||
| 43 | -- To address the above issues and ideas, AttnMask is directly enabled by default in MindSpeed, and the native mask generation method is no longer used. | 52 | +[1] To address the above issues and ideas, AttnMask is directly enabled by default in MindSpeed, and the native mask generation method is no longer used. |
| 44 | 53 | ||
| 45 | -- A global variable `mindspeed/model/transformer.py`-`global _GLOBAL_ATTN_MASK` is provided. | 54 | +[2] A global variable `_GLOBAL_ATTN_MASK` is provided in `mindspeed/core/transformer/flash_attention/generate_mask/generate_mask.py`. |
| 46 | 55 | ||
| 47 | -- The `--sparse-mode` parameter is provided to work with multiple FA modes. For information on the different modes of `--sparse-mode`, refer to the [torch_npu.npu_fusion_attention operator documentation](https://www.hiascend.com/document/detail/zh/Pytorch/60RC2/apiref/apilist/ptaoplist_001095.html). | 56 | +[3] The `--sparse-mode` parameter is provided to work with multiple FA modes. For information on the different modes of `--sparse-mode`, refer to the [torch_npu.npu_fusion_attention operator documentation](https://www.hiascend.com/document/detail/en/Pytorch/60RC2/apiref/apilist/ptaoplist_001095.html). |
| 48 | 57 | ||
| 49 | -- Three additional APIs `def set_attention_mask`, `def get_attention_mask`, and `def generate_attention_mask` are provided in `mindspeed/model/transformer.py` to implement setting, getting, and generation functions outside the normal flow. | 58 | +[4] Three additional APIs `set_attention_mask`, `get_attention_mask`, and `generate_attention_mask` are provided in `mindspeed/core/transformer/flash_attention/generate_mask/generate_mask.py` to implement setting, getting, and generation functions outside the normal flow. |
| 50 | 59 | ||
| 51 | -- Provides the `def parallel_transformer_forward_wrapper` API is provided in `mindspeed/model/transformer.py`, which bypasses the limitations of `get_batch` and enables `generate_attention_mask` to generate the mask during the first forward pass. | 60 | +[5] The local DotProductAttention generates the mask when it is first needed through `dot_product_attention_forward_wrapper` in `mindspeed/core/transformer/flash_attention/generate_mask/adaptor.py`; CP attention is handled by TENPU. |
| 52 | 61 | ||
| 53 | ## Effects | 62 | ## Effects |
| 54 | 63 | ||
| 55 | For example, in the lower triangular mode, setting sparse_mode=2 in compressed mode fixes the mask.shape to [2048, 2048], which significantly improves performance and reduces memory usage. | 64 | For example, in the lower triangular mode, setting sparse_mode=2 in compressed mode fixes the mask.shape to [2048, 2048], which significantly improves performance and reduces memory usage. |
| 56 | 65 | ||
| 57 | -> [!NOTE] | 66 | +## Notes |
| 58 | -> | 67 | + |
| 59 | -> Currently, the FA scenario only supports the lower triangular and Band modes. For other custom AttnMask modes, you need to manually set the attention mask or modify the `get_attention_mask` logic. | 68 | +The automatically generated FA mask is a causal mask; setting `general` does not automatically generate an arbitrary custom mask. `set_attention_mask` is only used to set the local cache and does not change the support restrictions of CP/EOD or `--sparse-mode`. |
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | -Currently, the communication domain buffer in MindSpeed can only be uniformly set through the environment variable `HCCL_BUFFSIZE` (default is 200 MB). However, the buffer sizes required by different communication domains often cannot be generalized. For details, see the [HCCL_BUFFSIZE](https://www.hiascend.com/document/detail/zh/CANNCommunityEdition/81RC1beta1/maintenref/envvar/envref_07_0001.html) section in *CANN Environment Variable Reference*. | 5 | +Currently, the communication domain buffer in MindSpeed can only be uniformly set through the environment variable `HCCL_BUFFSIZE` (default is 200 MB). However, the buffer sizes required by different communication domains often cannot be generalized. For details, see the [HCCL_BUFFSIZE](https://www.hiascend.com/document/detail/en/canncommercial/81RC1/apiref/envvar/envref_07_0080.html) section in *CANN Environment Variable Reference*. |
| 6 | 6 | ||
| 7 | ## Solution | 7 | ## Solution |
| 8 | 8 | ||
| @@ -15,20 +15,29 @@ This feature can be enabled in scenarios where memory is insufficient and memory | |||
| 15 | 15 | ||
| 16 | ## Usage | 16 | ## Usage |
| 17 | 17 | ||
| 18 | -* Auto-configuration for `--hccl-group-buffer-adaptive` | 18 | +* Auto-configuration |
| 19 | +`--hccl-group-buffer-adaptive` | ||
| 20 | +**Note:** | ||
| 19 | * When this feature is enabled, the buffer sizes for TP, CP, and PP communication groups are adaptively set. | 21 | * When this feature is enabled, the buffer sizes for TP, CP, and PP communication groups are adaptively set. |
| 20 | - * For EP communication groups (such as exp, tp_exp, tp), users can specify the coefficient `--hccl-ep-group-buffer-adaptive-factor` based on the MoE load imbalance degree of the current model to obtain an appropriate communication domain buffer. This coefficient represents the current load imbalance degree. For example, setting `--hccl-ep-group-buffer-adaptive-factor` to `1` indicates the buffer size required under load balancing conditions; setting it to `n` indicates that the current buffer size is `n` times that under load balancing conditions. Setting `n` too large may cause OOM. | 22 | + * For EP communication groups (such as exp, tp_exp, tp), users can specify the coefficient --hccl-ep-group-buffer-adaptive-factor based on the MoE load imbalance degree of the current model to obtain an appropriate communication domain buffer. This coefficient represents the current load imbalance degree. For example, setting --hccl-ep-group-buffer-adaptive-factor to 1 indicates the buffer size required under load balancing conditions; setting it to n indicates that the current buffer size is n times that under load balancing conditions. Setting n too large may cause OOM. |
| 21 | 23 | ||
| 22 | - * The communication groups currently supported by auto-configuration are as follows: [ "cp", "mp", "mp_exp", "tp", "pp", "tp_cp", "tp_exp", "exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra","cp_ring_intra_overlap"] | 24 | + * The communication groups currently supported by auto-configuration are as follows: |
| 25 | +[ "cp", "mp", "mp_exp", "tp", "pp", "tp_cp", "tp_exp", "exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra","cp_ring_intra_overlap"] | ||
| 23 | 26 | ||
| 24 | -* Manual configuration for `--hccl-group-buffer` | 27 | +* Manual configuration |
| 25 | - * Configure this parameter and specify the desired group and size (for example: `dp:200;tp:300;exp:400`), in MB. | 28 | +`--hccl-group-buffer` |
| 26 | - * The communication groups currently supported by manual configuration are as follows: ["dp", "dp_cp", "cp", "mp", "mp_exp", "tp", "pp", "embd", "tp_dp_cp", "tp_dp", "tp_cp", "tp_exp", "exp", "dp_modulo_exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring","cp_ring_intra", "cp_ring_intra_overlap", "nd1_dim1", "ag_x_sd_rcv_overlap", "nd1_dim2", "ag_y_sd_rcv_overlap", "nd2_dim1", "nd2_dim2"] | 29 | +**Note:** |
| 30 | + * Configure this parameter and specify the desired group and size (for example: `--hccl-group-buffer "dp:200;tp:300;ep:400"`, comma-separated values are also supported), in MB. The value must be a positive integer. | ||
| 31 | + * The communication groups currently supported by manual configuration are as follows: | ||
| 32 | +["dp", "dp_cp", "cp", "mp", "mp_exp", "tp", "pp", "embd", "tp_dp_cp", "tp_dp", "tp_cp", "tp_exp", "tp_ep_mp", "exp", "ep", "dp_modulo_exp", "pp_new_stream", "cp2", "cp_ulysses", "cp_ring", "cp_ring_intra", "cp_ring_intra_overlap", "nd1_dim1", "ag_x_sd_rcv_overlap", "nd1_dim2", "ag_y_sd_rcv_overlap", "nd2_dim1", "nd2_dim2", "default_group", "ep_dp", "ep_tp", "hcp", "inter_dp_cp", "inter_ep_dp", "inner_dp", "intra_dist_opt_instance", "intra_dp_cp", "intra_ep_dp", "pos_embd", "tp_ep_pp"] | ||
| 27 | 33 | ||
| 28 | -> [!NOTE] | 34 | +- `--hccl-op-mode` uses the same `group:integer` syntax, and the value must be a positive integer, for example, `--hccl-op-mode "tp:1,ep:1"`. |
| 29 | -> | 35 | +- This configuration can be used together with AI QoS. |
| 30 | -> This feature requires TorchNPU:FrameworkPTAdapter 7.0.RC1.B020 and its later version. | ||
| 31 | 36 | ||
| 32 | ## Effects | 37 | ## Effects |
| 33 | 38 | ||
| 34 | For Llama models, enabling the adaptive scheme can save memory without performance degradation; for MoE-related models, enabling the adaptive scheme and setting an appropriate load imbalance factor can save memory without performance degradation. | 39 | For Llama models, enabling the adaptive scheme can save memory without performance degradation; for MoE-related models, enabling the adaptive scheme and setting an appropriate load imbalance factor can save memory without performance degradation. |
| 40 | + | ||
| 41 | +## Usage Constraints | ||
| 42 | + | ||
| 43 | +This feature requires PTA:FrameworkPTAdapter 7.0.RC1.B020 and later versions (including this version). | ||
| @@ -4,9 +4,9 @@ | |||
| 4 | 4 | ||
| 5 | In large-scale clusters, Gloo communication faces scalability limitations and stability issues. On one hand, Gloo communication group creation failures are prone to occur; on the other hand, compared with HCCL communication, Gloo communication is slower. | 5 | In large-scale clusters, Gloo communication faces scalability limitations and stability issues. On one hand, Gloo communication group creation failures are prone to occur; on the other hand, compared with HCCL communication, Gloo communication is slower. |
| 6 | 6 | ||
| 7 | -For the issue of Gloo communication group creation failure with the error `Gloo connectFullMesh failed with ...`, the root cause is that N cards connect to the primary node for connection establishment. When the cluster scale is large, the primary node's processing capacity is insufficient, which may cause connection establishment failure. This can be mitigated by adjusting parameters related to network connection establishment (verified to be effective in an 8k-card cloud scenario): | 7 | +For the issue of Gloo communication group creation failure with the error `Gloo connectFullMesh failed with ...`, the root cause is that N cards connect to the primary Master for connection establishment. When the cluster scale is large, the Master's processing capacity is insufficient, which may cause connection establishment failure. This can be mitigated by adjusting parameters related to network connection establishment (verified to be effective in an 8k-card cloud scenario): |
| 8 | 8 | ||
| 9 | -```text | 9 | +```bash |
| 10 | net.ipv4.tcp_max_syn_backlog = 65536 | 10 | net.ipv4.tcp_max_syn_backlog = 65536 |
| 11 | net.core.netdev_max_backlog = 65536 | 11 | net.core.netdev_max_backlog = 65536 |
| 12 | ``` | 12 | ``` |
| @@ -15,9 +15,11 @@ Additionally, MindSpeed has designed a Gloo communication optimization solution | |||
| 15 | 15 | ||
| 16 | ## Solution | 16 | ## Solution |
| 17 | 17 | ||
| 18 | -- Replace the Gloo communication group with the HCCL communication group, achieving substitution on top of the existing functionality. | 18 | +### Approach |
| 19 | 19 | ||
| 20 | -- Use a slicing method to reduce the amount of data per communication, avoiding memory consumption caused by excessive communication volume. | 20 | +[1] Replace the Gloo communication group with the HCCL communication group, achieving substitution on top of the existing functionality. |
| 21 | + | ||
| 22 | +[2] Use a slicing method to reduce the amount of data per communication, avoiding memory consumption caused by excessive communication volume. | ||
| 21 | 23 | ||
| 22 | ## Application Scenario | 24 | ## Application Scenario |
| 23 | 25 | ||
| @@ -25,13 +27,13 @@ When Gloo communication frequently encounters connection establishment failures, | |||
| 25 | 27 | ||
| 26 | ## Usage | 28 | ## Usage |
| 27 | 29 | ||
| 28 | -1. Add `--disable-gloo-group` to the training script to enable this feature. | 30 | +[1] Add `--disable-gloo-group` to the training script to enable this feature. |
| 29 | 31 | ||
| 30 | -2. Define `--hccl-slice-size N` (optional) in the script to set the communication volume size when the DP group saves and loads distributed optimizer states. The valid range of this parameter is `(0, bucket_size/dp]`, where `bucket_size` is the size of each bucket in the distributed optimizer. It is recommended to increase this parameter as much as possible, provided that memory allows, to improve communication efficiency. | 32 | +[2] Define `--hccl-slice-size N` (optional) in the script to set the communication volume size when the DP group saves and loads distributed optimizer states. The valid range of this parameter is (0, bucket_size/dp], where bucket_size is the size of each bucket in the distributed optimizer. It is recommended to increase this parameter as much as possible, provided that memory allows, to improve communication efficiency. |
| 31 | 33 | ||
| 32 | ## Effects | 34 | ## Effects |
| 33 | 35 | ||
| 34 | -**Communication Efficiency Analysis** | 36 | +### Communication Efficiency Analysis |
| 35 | 37 | ||
| 36 | Theoretically, the communication efficiency of distributed optimizer state saving and loading improves as `hccl-slice-size` increases within a certain range. | 38 | Theoretically, the communication efficiency of distributed optimizer state saving and loading improves as `hccl-slice-size` increases within a certain range. |
| 37 | <!-- , Reference data: | 39 | <!-- , Reference data: |
| @@ -39,6 +41,6 @@ Theoretically, the communication efficiency of distributed optimizer state savin | |||
| 39 | - When the slice size is $30 * 1024 * 1024$, the model saving and loading efficiency is comparable to the original; | 41 | - When the slice size is $30 * 1024 * 1024$, the model saving and loading efficiency is comparable to the original; |
| 40 | - When the slice size is $100 * 1024 * 1024$, the model saving and loading efficiency improves to some extent. --> | 42 | - When the slice size is $100 * 1024 * 1024$, the model saving and loading efficiency improves to some extent. --> |
| 41 | 43 | ||
| 42 | -**Device Memory Increase Analysis** | 44 | +### Device Memory Increase Analysis |
| 43 | 45 | ||
| 44 | After enabling this feature, the increase in device memory is `hccl-slice-size * (2 * dp + 1) * 4B`. | 46 | After enabling this feature, the increase in device memory is `hccl-slice-size * (2 * dp + 1) * 4B`. |
| @@ -0,0 +1,129 @@ | |||
| 1 | +# HiF8 DTS (Delayed Tensor Scaling) Training | ||
| 2 | + | ||
| 3 | +## Background and Challenges | ||
| 4 | + | ||
| 5 | +HiF8 (Hybrid Float8) is a dynamic low-precision floating-point data format with 1 sign bit plus dynamic dot bits, exponent bits, and mantissa bits, with a maximum representable value of 2E15. Compared with the fixed-format E4M3 / E5M2, HiF8 balances a larger numerical representation range and higher precision by dynamically adjusting the bit-width allocation, making it suitable for a broader range of model structures and training scenarios. | ||
| 6 | + | ||
| 7 | +In HiF8 low-precision training, the strategy for computing the scaling factor directly determines the numerical stability of training. Delayed Tensor Scaling (DTS) is a delayed scaling strategy based on the historical amax: the recipe collects amax in the early stage of training and updates the scale factor at fixed intervals in the steady-state stage. Because DTS relies on historical statistics, when NaN/Inf occurs during training (such as abnormal batch data or gradient explosion), the contaminated amax history causes the scale factor of subsequent steps to become inaccurate, which in turn triggers continuous numerical overflow and eventually leads to training crash. | ||
| 8 | + | ||
| 9 | +## Solution | ||
| 10 | + | ||
| 11 | +MindSpeed provides the **Step Recovery** feature for HiF8 DTS training, which transactionally wraps `train_step` at the framework layer: | ||
| 12 | + | ||
| 13 | +1. **NaN/Inf detection**: Before the optimizer commit, check the loss, grad norm, and optimizer overflow flag to determine whether the current step is valid. | ||
| 14 | +2. **All-rank failure synchronization**: Synchronize the failure decision and failure reason across the world group via `all_reduce(MAX)` to ensure all ranks retry consistently, avoiding topology inconsistency caused by the optimizer all-reduce of pipeline-only ranks not being covered. | ||
| 15 | +3. **Transient state cleanup**: Clear gradients, the optimizer overflow flag, and pending asynchronous communication, but **do not touch** the parameter updates, optimizer momentum/variance, scheduler state, global step, and consumed-sample counters (these are committed only after a successful attempt). | ||
| 16 | +4. **HiF8 amax history reset**: Call the `FP8GlobalStateManager.reset_fp8_amax_history()` interface of TransformerEngineNPU to clear the contaminated amax history, so that subsequent steps restart from a clean scale factor. | ||
| 17 | +5. **RNG state restoration**: Restore the random number state of Python, NumPy, Torch CPU/Device, and the Megatron TP RNG tracker, so that dropout / random mask / MoE routing are reproduced as much as possible on retry. | ||
| 18 | +6. **Batch replay**: Cache the microbatches consumed by the original attempt and replay the same batch on retry, ensuring the continuity of the training data stream. Two modes are supported: | ||
| 19 | + - **ExternalReplayAdapter**: The framework layer caches the microbatches produced by the iterator, suitable for scenarios where the rerun state machine is not activated. Supports a `None` data_iterator (pipeline scenarios). | ||
| 20 | + - **NativeRerunReplayAdapter**: Implements replay based on Megatron `RerunDataIterator.saved_microbatches`, suitable for scenarios where the rerun state machine is activated. | ||
| 21 | +7. **Retry once**: After cleanup and reset, re-execute `train_step` using the restored RNG and the replayed batch. If the retry still fails, output a structured diagnostic log and raise a `RuntimeError`. | ||
| 22 | + | ||
| 23 | +The framework layer **does not maintain or read** the HiF8 warmup / CTS / DTS internal state; the only interaction point with TransformerEngineNPU is `reset_fp8_amax_history()`. | ||
| 24 | + | ||
| 25 | +## Additional Overhead of Normal Steps | ||
| 26 | + | ||
| 27 | +After Step Recovery is enabled, each normal step (without NaN/Inf) incurs **two** additional small `all_reduce(MAX)` collective communications: | ||
| 28 | + | ||
| 29 | +| Synchronization Point | Timing | Payload Size | Description | | ||
| 30 | +|--------|------|-------------|------| | ||
| 31 | +| `after_prepare_grads` | After the optimizer `prepare_grads()` returns | 2 x int32 | Synchronize the found_inf flag and the failure reason | | ||
| 32 | +| `before_step_with_ready_grads` | Before the optimizer `step_with_ready_grads()` is called | 2 x int32 | Synchronize the NaN/Inf detection result of loss/grad_norm | | ||
| 33 | + | ||
| 34 | +The payload of each `all_reduce` is only 2 int32 values (8 bytes), so the overhead is negligible. These two synchronization points ensure that when any rank detects an abnormality, all ranks can stop and retry consistently before the optimizer commit. | ||
| 35 | + | ||
| 36 | +In scenarios other than the `hif8_delayed` recipe, the wrapper short-circuits directly to the original `train_step`, with no additional overhead. | ||
| 37 | + | ||
| 38 | +## Application Scenario | ||
| 39 | + | ||
| 40 | +- When performing HiF8 DTS low-precision training with `--fp8-format hif8 --fp8-recipe hif8_delayed`, Step Recovery is enabled by default. | ||
| 41 | +- Scenarios where occasional NaN/Inf during training (such as abnormal data or gradient explosion) needs to be automatically recovered without interrupting training. | ||
| 42 | +- Scenarios that require continuity of the training data stream and do not want to skip batches. | ||
| 43 | + | ||
| 44 | +## Usage | ||
| 45 | + | ||
| 46 | +### Basic Enabling | ||
| 47 | + | ||
| 48 | +HiF8 DTS training is enabled through the following parameter combination, and Step Recovery is automatically activated accordingly: | ||
| 49 | + | ||
| 50 | +```bash | ||
| 51 | +--transformer-impl transformer_engine | ||
| 52 | +--fp8-format hif8 | ||
| 53 | +--fp8-recipe hif8_delayed | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +### Explicitly Disabling Step Recovery | ||
| 57 | + | ||
| 58 | +To disable Step Recovery (for example, for debugging or comparing with a baseline), add: | ||
| 59 | + | ||
| 60 | +```bash | ||
| 61 | +--no-hif8-step-recovery | ||
| 62 | +``` | ||
| 63 | + | ||
| 64 | +### HiF8 DTS Configuration Parameters | ||
| 65 | + | ||
| 66 | +The HiF8 DTS recipe provides the following tunable parameters, which are used to control the amax collection and scale factor update behavior: | ||
| 67 | + | ||
| 68 | +| Parameter | Type | Default | Description | | ||
| 69 | +|------|------|--------|------| | ||
| 70 | +| `--hif8-input-margin` | int | 11 | Number of guard bits for input/activation tensors, recommended range 9-11 | | ||
| 71 | +| `--hif8-weight-margin` | int | 12 | Number of guard bits for weight tensors, recommended range 11-12 | | ||
| 72 | +| `--hif8-grad-margin` | int | 11 | Number of guard bits for gradient tensors, recommended range 9-11 | | ||
| 73 | +| `--hif8-amax-collect-interval` | int | 5 | Length of the warmup stage (number of iterations). During this period, amax is collected at every step; recommended range 5-20 | | ||
| 74 | +| `--hif8-scale-update-interval` | int | 10 | Interval for amax history collection and scale factor update in the steady-state stage (number of iterations) | | ||
| 75 | +| `--hif8-amax-history-len` | int | 128 | Length of the amax history buffer, recommended values 64 / 128 / 256 | | ||
| 76 | +| `--no-hif8-step-recovery` | flag | False | Disable HiF8 NaN/Inf Step Recovery | | ||
| 77 | + | ||
| 78 | +## Usage Impact | ||
| 79 | + | ||
| 80 | +- **Training continuity**: After detecting NaN/Inf, Step Recovery retries the same batch instead of skipping it, ensuring the continuity of the training data stream and avoiding convergence drift. | ||
| 81 | +- **Numerical stability**: By resetting the HiF8 amax history, it eliminates the impact of the contaminated scale factor on subsequent steps and avoids cascading failures. | ||
| 82 | +- **Determinism**: By restoring the complete RNG state, the retry attempt reproduces the random behavior of the original attempt as much as possible (dropout, mask, routing, etc.). | ||
| 83 | +- **Overhead**: Additional overhead is incurred only when NaN/Inf is detected (cleanup, reset, RNG restoration, batch replay, and one extra forward/backward pass). The additional overhead of a normal step is only two 2 x int32 `all_reduce(MAX)` operations, which is negligible. The wrapper short-circuits directly in scenarios other than `hif8_delayed`. | ||
| 84 | +- **Retry limit**: Each step is retried at most once. If the retry still fails, training is aborted and a structured diagnostic log is output (including iteration, reason, rank, loss, and grad_norm). | ||
| 85 | + | ||
| 86 | +## Parameter Combination Restrictions | ||
| 87 | + | ||
| 88 | +The `hif8_delayed` recipe is only allowed to be used in combination with `--fp8-format hif8`. Combining other fp8-format values (such as `e4m3`) with `hif8_delayed` reports an error during the parameter validation stage. | ||
| 89 | + | ||
| 90 | +<table><thead> | ||
| 91 | + <tr> | ||
| 92 | + <th width='120'>Feature</th> | ||
| 93 | + <th>Combination</th> | ||
| 94 | + <th>Supported</th> | ||
| 95 | + </tr></thead> | ||
| 96 | +<tbody> | ||
| 97 | + <tr> | ||
| 98 | + <td rowspan="3">HiF8 DTS training</td> | ||
| 99 | + <td rowspan="3">--transformer-impl transformer_engine | ||
| 100 | + <br> --fp8-format hif8 | ||
| 101 | + <br> --fp8-recipe hif8_delayed </td> | ||
| 102 | + <td style="text-align: center; vertical-align: middle">✅</td> | ||
| 103 | + </tr> | ||
| 104 | +</tbody> | ||
| 105 | +<tbody> | ||
| 106 | + <tr> | ||
| 107 | + <td rowspan="3">HiF8 DTS + Step Recovery</td> | ||
| 108 | + <td rowspan="3">--transformer-impl transformer_engine | ||
| 109 | + <br> --fp8-format hif8 | ||
| 110 | + <br> --fp8-recipe hif8_delayed | ||
| 111 | + <br>(Enabled by default, no additional parameters required)</td> | ||
| 112 | + <td style="text-align: center; vertical-align: middle">✅</td> | ||
| 113 | + </tr> | ||
| 114 | +</tbody> | ||
| 115 | +<tbody> | ||
| 116 | + <tr> | ||
| 117 | + <td rowspan="3">HiF8 DTS + Explicitly Disabling Step Recovery</td> | ||
| 118 | + <td rowspan="3">--transformer-impl transformer_engine | ||
| 119 | + <br> --fp8-format hif8 | ||
| 120 | + <br> --fp8-recipe hif8_delayed | ||
| 121 | + <br> --no-hif8-step-recovery </td> | ||
| 122 | + <td style="text-align: center; vertical-align: middle">✅</td> | ||
| 123 | + </tr> | ||
| 124 | +</tbody> | ||
| 125 | +</table> | ||
| 126 | + | ||
| 127 | +## Related Feature References | ||
| 128 | + | ||
| 129 | +- **[Megatron Transformer-engine](transformer_engine.md)**: An overall introduction to the TE module, including the HiF8 data format, low-precision training scaling strategies, and a description of the TE module features. | ||
| @@ -1,71 +0,0 @@ | |||
| 1 | -# Hybrid Long-Sequence Parallelism | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -From generative AI to scientific research models, long sequence training is becoming increasingly important. In the generative AI domain, tasks such as conversational AI, long document summarization, and video generation all require reasoning over long contexts in both spatial and temporal dimensions. Similarly, chapter-level and book-level summarization (involving tens or even hundreds of thousands of words) is also valued in conversational AI and summarization tasks. Existing parallelism methods such as data, tensor, and pipeline parallelism cannot perform partitioning along the sequence dimension. As the sequence dimension (S) grows, the training memory overhead increases at a rate of $O$($S^2$). Therefore, specific optimizations are needed for long sequence scenarios to meet the training requirements of long training scenarios. | ||
| 6 | - | ||
| 7 | -Popular sequence parallelism schemes, Ulysses and Ring Attention, each have their own limitations. | ||
| 8 | - | ||
| 9 | -Ulysses requires that the number of attention heads be divisible by the sequence parallelism dimension. In GQA and MQA scenarios, the size of sequence parallelism is limited, resulting in limited expansion of the sequence length. | ||
| 10 | - | ||
| 11 | -The parallelism dimension of Ring Attention is not limited by the number of attention heads, so the sequence length can theoretically be extended indefinitely. However, compared to Ulysses, Ring Attention cannot fully utilize communication and computation bandwidth, and its performance is inferior to Ulysses when the sequence chunk size is small. | ||
| 12 | - | ||
| 13 | -## Solution | ||
| 14 | - | ||
| 15 | -Ulysses and Ring Attention are fused to implement hybrid sequence parallelism, thereby addressing the respective shortcomings of both approaches. For details, see the paper [USP: A Unified Sequence Parallelism Approach for Long Context Generative AI](https://arxiv.org/abs/2405.07719). | ||
| 16 | - | ||
| 17 | -## Application Scenario | ||
| 18 | - | ||
| 19 | -The hybrid long-sequence parallel scheme is applicable to the following typical scenarios: | ||
| 20 | - | ||
| 21 | -- It is compatible with FlashAttention, which is currently enabled by default. | ||
| 22 | - | ||
| 23 | -- The SP dimension is divided into the Ulysses dimension and the Ring Attention dimension. The product of the Ulysses dimension and the Ring Attention dimension equals the overall sequence parallel dimension. | ||
| 24 | - | ||
| 25 | -## Usage | ||
| 26 | - | ||
| 27 | -<table> | ||
| 28 | - <thead> | ||
| 29 | - <tr> | ||
| 30 | - <th width='200'>Important Parameter</th> | ||
| 31 | - <th>Description</th> | ||
| 32 | - <th>Required</th> | ||
| 33 | - <th>Default Value</th> | ||
| 34 | - </tr> | ||
| 35 | - </thead> | ||
| 36 | - <tbody> | ||
| 37 | - <tr> | ||
| 38 | - <td> --context-parallel-size [int]</td> | ||
| 39 | - <td>Sets the long-sequence parallel size. The default is 1; configure according to user requirements.</td> | ||
| 40 | - <td>No</td> | ||
| 41 | - <td>1</td> | ||
| 42 | - </tr> | ||
| 43 | - <tr> | ||
| 44 | - <td> --ulysses-degree-in-cp [int]</td> | ||
| 45 | - <td>This parameter must be greater than 1, and --context-parallel-size must be divisible by this parameter. For example, when --context-parallel-size is set to 8, you can set --ulysses-degree-in-cp to 2 or --ulysses-degree-in-cp to 4. | ||
| 46 | - <br>Additionally, ensure that --num-attention-heads is divisible by the product of --ulysses-degree-in-cp * --tensor-model-parallel-size. | ||
| 47 | - </td> | ||
| 48 | - <td>/</td> | ||
| 49 | - <td>/</td> | ||
| 50 | - </tr> | ||
| 51 | - <tr> | ||
| 52 | - <td> --context-parallel-algo</td> | ||
| 53 | - <td> | ||
| 54 | - Long-sequence parallel algorithm options: | ||
| 55 | - <ul> | ||
| 56 | - <li><code>ulysses_cp_algo</code>: Enables Ulysses long-sequence parallelism</li> | ||
| 57 | - <li><b>hybrid_cp_algo</b>: Enables Hybrid long-sequence parallelism</li> | ||
| 58 | - <li><code>megatron_cp_algo</code>: Enables Ring Attention long-sequence parallelism</li> | ||
| 59 | - </ul> | ||
| 60 | - </td> | ||
| 61 | - <td>No</td> | ||
| 62 | - <td>megatron_cp_algo</td> | ||
| 63 | - </tr> | ||
| 64 | - </tbody> | ||
| 65 | -</table> | ||
| 66 | - | ||
| 67 | -Hybrid long-sequence parallelism supports Ring Attention long sequence parallelism-related features, including send-receive overlap functionality and mask computation type configuration. | ||
| 68 | - | ||
| 69 | -## Effects | ||
| 70 | - | ||
| 71 | -By leveraging multiple compute devices to partition the input sequence in parallel, the memory consumption of a single device is reduced. Compared to not enabling sequence parallelism, the per-step time increases, but computational efficiency is improved compared to recomputation. | ||
| @@ -14,19 +14,30 @@ For more details on the KVAllGather long-sequence parallelism scheme, see the or | |||
| 14 | 14 | ||
| 15 | ## Application Scenario | 15 | ## Application Scenario |
| 16 | 16 | ||
| 17 | -The KVAllGather long-sequence parallelism scheme is highly versatile, flexibly supporting various attention masks with minimal constraints in practical apps. | 17 | +**Backend limitation:** When CP>1, `--transformer-impl transformer_engine` must be set. |
| 18 | + | ||
| 19 | +KVAllGather computes the attention corresponding to the local query by gathering the complete keys and values. For the supported mask scope, see the notes below. | ||
| 18 | 20 | ||
| 19 | In scenarios such as GQA (Grouped-Query Attention) and MQA (Multi-Query Attention), the time required for all-gather communication of keys and values is far less than the overall computation time, making the benefits of this scheme even more significant. | 21 | In scenarios such as GQA (Grouped-Query Attention) and MQA (Multi-Query Attention), the time required for all-gather communication of keys and values is far less than the overall computation time, making the benefits of this scheme even more significant. |
| 20 | 22 | ||
| 21 | -This approach is fully compatible with FlashAttention, which is enabled by default for accelerated computation. | 23 | +This approach is fully compatible with Flash Attention, which is enabled by default for accelerated computation. |
| 22 | 24 | ||
| 23 | ## Usage | 25 | ## Usage |
| 24 | 26 | ||
| 27 | +| Training Type | Supported Mask Types | | ||
| 28 | +| --- | --- | | ||
| 29 | +| Standard training | causal | | ||
| 30 | +| EOD Reset | causal, and the [EOD Reset configuration constraints](eod-reset.md) must be satisfied | | ||
| 31 | + | ||
| 32 | +`--cp-comm-type allgather` is equivalent to `all_gather`. | ||
| 33 | + | ||
| 34 | +Use `--cp-comm-type` to select the communication mode. | ||
| 35 | + | ||
| 25 | | Important Parameter | Parameter Description | | 36 | | Important Parameter | Parameter Description | |
| 26 | -| ---------------------------------------------------- | --------------------------------------------------------- | | 37 | +|----------------------------------------------------|---------------------------------------------------------| |
| 27 | -| `--context-parallel-size [int]` | Sets the number of parallel processes for CP. The default is `1` (parallelism disabled). To enable parallelism, set this value to greater than `1` according to user requirements. | | 38 | +| --context-parallel-size [int] | Sets the number of processes for CP. The default is 1; configure according to user requirements. | |
| 28 | -| `--context-parallel-algo kvallgather_cp_algo` | Long-sequence parallel algorithm option. Set to `kvallgather_cp_algo` to enable KVAllGather long-sequence parallelism. | | 39 | +| --cp-comm-type <b>all_gather</b> | Long-sequence parallel algorithm option. Set to `all_gather` to enable KVAllGather long-sequence parallelism. | |
| 29 | -| `--seq-length [int]` | The length of the input sequence. | | 40 | +| --seq-length [int] | The length of the input sequence. | |
| 30 | 41 | ||
| 31 | ## Effects | 42 | ## Effects |
| 32 | 43 | ||
| @@ -35,6 +46,6 @@ By partitioning the input sequence across multiple compute devices, this approac | |||
| 35 | ## Notes | 46 | ## Notes |
| 36 | 47 | ||
| 37 | 1. When enabling KVAllGather long sequence parallelism, you must also set `--transformer-impl transformer_engine`; otherwise, the feature is not supported. | 48 | 1. When enabling KVAllGather long sequence parallelism, you must also set `--transformer-impl transformer_engine`; otherwise, the feature is not supported. |
| 38 | -2. Currently, only `--attention-mask-type` set to `causal` is supported. | 49 | +2. Both standard training and EOD Reset only support `--attention-mask-type causal`. |
| 39 | 3. For fixed-length padding training scenarios, a load-balanced sequence partitioning method is used, and `--seq-length` must be divisible by `2 * context-parallel-size`. | 50 | 3. For fixed-length padding training scenarios, a load-balanced sequence partitioning method is used, and `--seq-length` must be divisible by `2 * context-parallel-size`. |
| 40 | -4. For EOD Reset training scenarios, a conventional sequence partitioning method is used, and `--seq-length` must be divisible by context-parallel-size. | 51 | +4. For EOD Reset, `--variable-seq-lengths --micro-batch-size 1` must be set, and all layers uniformly use `all_gather`; the Ring-based per-document online padding is not used. The sequence length still needs to satisfy the native CP partitioning requirements. |
| @@ -1,38 +0,0 @@ | |||
| 1 | -# Low-Precision Optimizer | ||
| 2 | - | ||
| 3 | -## Problem Analysis | ||
| 4 | - | ||
| 5 | -In large model training scenarios, Adam-type optimizers continuously save parameter copies, gradients, and first- and second-order momentum of the optimizer using FP32 full-precision data types during training, resulting in significant static memory usage. | ||
| 6 | - | ||
| 7 | - | ||
| 8 | - | ||
| 9 | -## Solution | ||
| 10 | - | ||
| 11 | -Quantize and compress the data stored in the optimizer to low precision respectively, to reduce memory usage: | ||
| 12 | - | ||
| 13 | -1. Quantize the momentum in the optimizer to the E4M3 format FP8, HiF8, or MXFP8 data type, reducing momentum memory usage. | ||
| 14 | -2. Quantize gradients to half-precision FP16, reducing gradient memory usage. | ||
| 15 | -3. Adapt the existing parameter replica reuse algorithm to reduce parameter replica memory usage. | ||
| 16 | - | ||
| 17 | - | ||
| 18 | - | ||
| 19 | -Before the optimizer updates parameters, the quantized data must first be dequantized to FP32 to ensure computational accuracy. After the update is complete, it is quantized back to low precision. The computation workflow is shown in the following diagram: | ||
| 20 | - | ||
| 21 | - | ||
| 22 | - | ||
| 23 | -## Usage | ||
| 24 | - | ||
| 25 | -Set `--quant-states <fp8|hif8|mxfp8>` to enable optimizer momentum quantization. The quantization data type can be `fp8`, `hif8`, or `mxfp8`. | ||
| 26 | - | ||
| 27 | -Set `--quant-grads` to enable gradient quantization compression. Gradients are quantized from the FP32 data type to FP16. | ||
| 28 | - | ||
| 29 | -Compatible with the `reuse-fp32-param` feature | ||
| 30 | - | ||
| 31 | -## Effects | ||
| 32 | - | ||
| 33 | -Reduces the static memory usage of the optimizer. | ||
| 34 | - | ||
| 35 | -## Usage Constraints | ||
| 36 | - | ||
| 37 | -1. `--quant-grads` does not support `--gemm-gradient-accumulation-fusion`. You need to enable `--no-gradient-accumulation-fusion` to disable gradient accumulation fusion. | ||
| 38 | -2. `--quant-grads` and `--quant-states` do not support `--swap-optimizer`. To use the low-precision optimizer, you need to disable the `--swap-optimizer` feature. | ||
| @@ -2,6 +2,8 @@ | |||
| 2 | 2 | ||
| 3 | ## Prerequisites | 3 | ## Prerequisites |
| 4 | 4 | ||
| 5 | +**Backend limitation:** MC2 only applies to the native ColumnParallelLinear/RowParallelLinear and does not cover the linear layers under the TE path (`--transformer-impl transformer_engine`, implemented by TENPU on Ascend). | ||
| 6 | + | ||
| 5 | Only applicable to system environments with version identifiers `CANN 8.0.RC2` and `Ascend HDK 24.1.RC2`, and all subsequent iterative versions. | 7 | Only applicable to system environments with version identifiers `CANN 8.0.RC2` and `Ascend HDK 24.1.RC2`, and all subsequent iterative versions. |
| 6 | 8 | ||
| 7 | Attempting to use this configuration on non-specified versions may trigger system-level abnormal behavior, including but not limited to runtime errors. | 9 | Attempting to use this configuration on non-specified versions may trigger system-level abnormal behavior, including but not limited to runtime errors. |
| @@ -48,11 +50,50 @@ for name, module in model.named_modules(): | |||
| 48 | param.requires_grad = False | 50 | param.requires_grad = False |
| 49 | ``` | 51 | ``` |
| 50 | 52 | ||
| 53 | +> [!NOTE] | ||
| 54 | +> | ||
| 55 | +> **Applicable scope**: Example 2 only applies to the `--transformer-impl local` path. Under the `--transformer-impl transformer_engine` path, the linear layers are Megatron's TE wrapper classes and are not subclasses of `ColumnParallelLinear` / `RowParallelLinear`; `isinstance` is always `False` - **silent freezing failure: no error, no printing, and no parameters are frozen**. | ||
| 56 | + | ||
| 57 | +The classes of the linear layers under the two paths: | ||
| 58 | + | ||
| 59 | +| Module | `local` | `transformer_engine` | | ||
| 60 | +| --- | --- | --- | | ||
| 61 | +| `self_attention.linear_qkv` | `ColumnParallelLinear` | `TELayerNormColumnParallelLinear` | | ||
| 62 | +| `mlp.linear_fc1` | `ColumnParallelLinear` | `TELayerNormColumnParallelLinear` | | ||
| 63 | +| `self_attention.linear_proj` | `RowParallelLinear` | `TERowParallelLinear` | | ||
| 64 | +| `mlp.linear_fc2` | `RowParallelLinear` | `TERowParallelLinear` | | ||
| 65 | + | ||
| 66 | +- `local`: The linear layers use Megatron's native implementation; after enabling `--use-ascend-mc2`, they are replaced by `MindSpeedMC2Column/RowParallelLinear`, which still inherit from the native classes, so the `isinstance` check in Example 2 still matches. | ||
| 67 | +- `transformer_engine`: On Ascend, the implementation is provided by TENPU (the `transformer_engine` package in the environment); the model's linear layers are Megatron's TE wrapper classes, located in `megatron.core.extensions.transformer_engine`, inheriting from TENPU's `te.pytorch.Linear` / `LayerNormLinear`. | ||
| 68 | +- `TELayerNormColumnParallelLinear` incorporates LayerNorm and does not inherit from `TELinear`, so it must be matched separately; its `layer_norm_weight` remains trainable. | ||
| 69 | + | ||
| 70 | +```python | ||
| 71 | +# Example 3: freeze all column + row linear layers, applicable to both paths | ||
| 72 | +from megatron.core.tensor_parallel.layers import ColumnParallelLinear, RowParallelLinear | ||
| 73 | +from megatron.core.extensions.transformer_engine import TEColumnParallelLinear, TERowParallelLinear | ||
| 74 | +from megatron.core.extensions.transformer_engine import TELayerNormColumnParallelLinear | ||
| 75 | + | ||
| 76 | +FREEZE_TYPES = (ColumnParallelLinear, RowParallelLinear, | ||
| 77 | + TEColumnParallelLinear, TERowParallelLinear, TELayerNormColumnParallelLinear) | ||
| 78 | +for name, module in model.named_modules(): | ||
| 79 | + if 'output_layer' in name or not isinstance(module, FREEZE_TYPES): | ||
| 80 | + continue | ||
| 81 | + for param_name, param in module.named_parameters(recurse=False): | ||
| 82 | + if 'norm' in param_name: # LayerNorm fused into the linear layer, kept trainable | ||
| 83 | + continue | ||
| 84 | + param.requires_grad = False | ||
| 85 | + print(f'rank:{torch.distributed.get_rank()}, frozen: {name}') | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +Example 3 must import the TE wrapper classes from `megatron.core.extensions.transformer_engine` (the model instance is exactly an instance of this class); `transformer_engine.pytorch.*` are TENPU's base classes, and the model contains no such instances; once TENPU changes to no longer inherit from them, it will silently fail again. | ||
| 89 | + | ||
| 90 | +The failure is silent, so it is recommended to keep the printing and assert the count in CI: `number of ranks x (num_layers / pipeline_model_parallel_size) x 4` (with 8 devices/8 layers/PP=2, this equals 128, and freezing only row gives 64). | ||
| 91 | + | ||
| 51 | ## Usage | 92 | ## Usage |
| 52 | 93 | ||
| 53 | -Set `--use-ascend-mc2` to enable the MC2 operator. | 94 | +For the native linear layer path, set `--transformer-impl local --use-ascend-mc2` to enable the MC2 operator. |
| 54 | 95 | ||
| 55 | -**You must also enable** `--sequence-parallel`. | 96 | +TP must be greater than 1, and `--sequence-parallel` must be enabled. |
| 56 | 97 | ||
| 57 | ## Effects | 98 | ## Effects |
| 58 | 99 | ||
| @@ -61,5 +102,5 @@ In training scenarios with TP and SP enabled, using MC2 can reduce memory overhe | |||
| 61 | ## Notes | 102 | ## Notes |
| 62 | 103 | ||
| 63 | 1. MoE models do not currently support enabling MC2. | 104 | 1. MoE models do not currently support enabling MC2. |
| 64 | -2. The compute-communication parallel CoC feature `--use-ascend-coc` is not currently compatible. | 105 | +2. In FP8 scenarios, only the `mxfp8` recipe is supported. |
| 65 | 3. This feature is not supported on Atlas 900 A3 hardware. | 106 | 3. This feature is not supported on Atlas 900 A3 hardware. |
| @@ -2,7 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | -### Gather/Scatter Replacement | 5 | +### 1. Gather/Scatter Replacement |
| 6 | 6 | ||
| 7 | In the Allgather branch of Megatron MoE, gather/scatter operations are used. The gather/scatter functionality performs element-wise value retrieval/assignment along a dimension axis based on indices. This operation involves a large number of random memory addresses, which significantly impacts performance. | 7 | In the Allgather branch of Megatron MoE, gather/scatter operations are used. The gather/scatter functionality performs element-wise value retrieval/assignment along a dimension axis based on indices. This operation involves a large number of random memory addresses, which significantly impacts performance. |
| 8 | 8 | ||
| @@ -13,28 +13,38 @@ self.global_local_map = global_local_map.view(-1, 1).expand(-1, hidden_states.sh | |||
| 13 | local_hidden_states = torch.gather(global_hidden_states, 0, self.global_local_map) | 13 | local_hidden_states = torch.gather(global_hidden_states, 0, self.global_local_map) |
| 14 | ``` | 14 | ``` |
| 15 | 15 | ||
| 16 | -### Asynchronous Communication | 16 | +### 2. Asynchronous Communication |
| 17 | 17 | ||
| 18 | In the Allgather dispatcher branch, the permute function performs allgather communication on three data items—hidden_states, max_ind, and max_prob—at the beginning. These operations are serial, but there is no serial dependency between the individual computation tasks. | 18 | In the Allgather dispatcher branch, the permute function performs allgather communication on three data items—hidden_states, max_ind, and max_prob—at the beginning. These operations are serial, but there is no serial dependency between the individual computation tasks. |
| 19 | 19 | ||
| 20 | ## Solution | 20 | ## Solution |
| 21 | 21 | ||
| 22 | -### Gather/Scatter Replacement | 22 | +### 1. Gather/Scatter Replacement |
| 23 | 23 | ||
| 24 | Since index is expanded via expand, the content in each of its rows is identical. There is no need to use gather/scatter for element-wise operations. Instead, the index and indexput operators can be used for row-wise operations, achieving an equivalent substitution for gather/scatter. | 24 | Since index is expanded via expand, the content in each of its rows is identical. There is no need to use gather/scatter for element-wise operations. Instead, the index and indexput operators can be used for row-wise operations, achieving an equivalent substitution for gather/scatter. |
| 25 | 25 | ||
| 26 | -### Asynchronous Communication | 26 | +### 2. Asynchronous Communication |
| 27 | 27 | ||
| 28 | By reordering communication tasks and issuing them asynchronously using the async=True parameter, computation and communication can be overlapped. | 28 | By reordering communication tasks and issuing them asynchronously using the async=True parameter, computation and communication can be overlapped. |
| 29 | 29 | ||
| 30 | ## Application Scenario | 30 | ## Application Scenario |
| 31 | 31 | ||
| 32 | -This optimization strategy applies to deep learning models deployed with the Mcore MoE (Mixture of Experts) architecture, with the `--moe-token-dispatcher-type allgather` flag enabled. | 32 | +**Backend limitation:** When enabling the communication overlap optimization described in this document, `--moe-grouped-gemm --transformer-impl transformer_engine` must be set. |
| 33 | + | ||
| 34 | +This optimization strategy applies to deep learning models deployed with the Mcore MoE (Mixture of Experts) architecture, | ||
| 35 | +with the `--moe-token-dispatcher-type allgather` flag enabled. | ||
| 33 | 36 | ||
| 34 | ## Usage | 37 | ## Usage |
| 35 | 38 | ||
| 36 | -Enable the parameter `--moe-permutation-async-comm`. | 39 | +Set `--moe-token-dispatcher-type allgather` to select the Allgather dispatcher (the default type). For the supported scope of each dispatcher type, see [the type table](megatron-moe-alltoall-dispatcher.md#usage). |
| 40 | + | ||
| 41 | +When enabling the asynchronous communication optimization, use `--moe-permutation-async-comm`, and refer to [Allgather Communication Overlap](megatron-moe-allgather-overlap-comm.md) to also configure `--moe-allgather-overlap-comm`, `--moe-grouped-gemm`, and `--transformer-impl transformer_engine`. | ||
| 42 | + | ||
| 43 | +## Usage Constraints | ||
| 44 | + | ||
| 45 | +- `--variable-seq-lengths` is not supported, including the CP+EOD scenarios that require this option; in such cases, use `alltoall`. | ||
| 46 | +- `--moe-permute-fusion` and `--moe-shared-expert-overlap` are not supported; Allgather communication overlap uses the dedicated configuration mentioned above. | ||
| 37 | 47 | ||
| 38 | ## Effects | 48 | ## Effects |
| 39 | 49 | ||
| 40 | -According to actual test data, after applying the above optimization measures to a DeepSeek-V2-like MoE model, the end-to-end training throughput is improved by approximately 10%, and the wall-clock time for the same number of training steps is reduced accordingly. | 50 | +According to actual test data, for a DeepSeek-V2-like MoE model at the billion-parameter level, after applying the above optimization measures, the end-to-end training performance improves by approximately 10%. This means it not only accelerates model convergence but also reduces the computing resources required to reach the same level of accuracy. |
| @@ -6,20 +6,25 @@ In MoE, a large amount of EP communication is not hidden, accounting for a signi | |||
| 6 | 6 | ||
| 7 | ## Solution | 7 | ## Solution |
| 8 | 8 | ||
| 9 | -During the forward pass, asynchronous communication is used to overlap with computation as much as possible. At the same time, the entire computation flow is split into subgraphs, enabling communication-computation overlap during the backward pass as well, thereby accelerating model training. This feature is specifically optimized for the `allgather dispatcher`. | 9 | +During the forward pass, asynchronous communication is used to overlap with computation as much as possible. At the same time, the entire computation flow is split into subgraphs, enabling communication-computation overlap during the backward pass as well, thereby accelerating model training. |
| 10 | +This feature is specifically optimized for the `allgather` dispatcher. | ||
| 10 | 11 | ||
| 11 | ## Usage | 12 | ## Usage |
| 12 | 13 | ||
| 13 | -- Enable this feature by turning on `--moe-allgather-overlap-comm`. | 14 | +**Backend limitation:** `--transformer-impl transformer_engine` must be set, and `local` is not supported. |
| 14 | -- The following must also be enabled: | 15 | + |
| 15 | - - `--moe-permutation-async-comm` | 16 | +Enable this feature by turning on `--moe-allgather-overlap-comm`. |
| 16 | - - `--moe-token-dispatcher-type allgather` | 17 | + |
| 17 | - - `--moe-grouped-gemm`, currently only supports Grouped MLP. | 18 | +The following must also be enabled: |
| 19 | + | ||
| 20 | +- `--moe-permutation-async-comm` | ||
| 21 | +- `--moe-token-dispatcher-type allgather` | ||
| 22 | +- `--moe-grouped-gemm`, using TEGroupedMLP. | ||
| 23 | +- `--transformer-impl transformer_engine`. | ||
| 24 | + | ||
| 25 | +Only `allgather` is supported; `alltoall` and `flex` are not supported. `--variable-seq-lengths` is not supported; `--recompute-activation-function` cannot be used together with `--hybrid-layer-pattern`. | ||
| 18 | 26 | ||
| 19 | ## Application Scenario | 27 | ## Application Scenario |
| 20 | 28 | ||
| 21 | Applicable to megatron-moe, specifically the dropless scheme branch, when EP communication becomes a bottleneck and communication overlap for EP communication is needed. | 29 | Applicable to megatron-moe, specifically the dropless scheme branch, when EP communication becomes a bottleneck and communication overlap for EP communication is needed. |
| 22 | - | 30 | +Enabling this feature will increase memory usage, which is expected behavior. |
| 23 | -> [!NOTE] | ||
| 24 | -> | ||
| 25 | -> Enabling this feature will increase memory usage, which is expected behavior. | ||
| @@ -2,35 +2,43 @@ | |||
| 2 | 2 | ||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | -**repeat_interleave Parallelism** | 5 | +### 1. repeat_interleave Parallelism |
| 6 | 6 | ||
| 7 | In the Alltoall dispatcher branch, the repeat_interleave operator is invoked. This operator uses only a single block dimension for serial computation on a single launch stream, resulting in long execution times. Moreover, the operator's output is not used until after the alltoall, permute, and alltoallv operations. | 7 | In the Alltoall dispatcher branch, the repeat_interleave operator is invoked. This operator uses only a single block dimension for serial computation on a single launch stream, resulting in long execution times. Moreover, the operator's output is not used until after the alltoall, permute, and alltoallv operations. |
| 8 | 8 | ||
| 9 | -**Computation-Communication Overlapping** | 9 | +### 2. Computation-Communication Overlapping |
| 10 | 10 | ||
| 11 | In the alltoall branch, the permutation function performs an allgather operation to complete the split H dimension of all tokens, and then performs expert computation on the data blocks. This operation is serial, but since there is no dependency between tokens of different experts, it can be modified to a parallel operation. | 11 | In the alltoall branch, the permutation function performs an allgather operation to complete the split H dimension of all tokens, and then performs expert computation on the data blocks. This operation is serial, but since there is no dependency between tokens of different experts, it can be modified to a parallel operation. |
| 12 | 12 | ||
| 13 | ## Solution | 13 | ## Solution |
| 14 | 14 | ||
| 15 | -**For repeat_interleave Parallelism** | 15 | +### 1. repeat_interleave Parallelism |
| 16 | 16 | ||
| 17 | By creating a new dispatch stream, the repeat_interleave operator invocation is offloaded to the new stream. When block dim resources are sufficient, the two operators can be computed in parallel, saving time. | 17 | By creating a new dispatch stream, the repeat_interleave operator invocation is offloaded to the new stream. When block dim resources are sufficient, the two operators can be computed in parallel, saving time. |
| 18 | 18 | ||
| 19 | -**For Computation-Communication Overlapping** | 19 | +### 2. Computation-Communication Overlapping |
| 20 | 20 | ||
| 21 | -Tokens can be split according to the requirements of each expert, and then allgather communication and expert computation are performed on the tokens one by one. Since the computation of the first expert depends only on the first communication and there is no dependency between experts, the communication for the second expert can proceed concurrently while the first expert's computation is being performed, achieving computation-communication overlapping. | 21 | +Tokens can be split according to the requirements of each expert, and then allgather communication + expert computation are performed on the tokens one by one. Since the computation of the first expert depends only on the first communication and there is no dependency between experts, the communication for the second expert can proceed concurrently while the first expert's computation is being performed, achieving computation-communication overlapping. |
| 22 | 22 | ||
| 23 | ## Application Scenario | 23 | ## Application Scenario |
| 24 | 24 | ||
| 25 | +**Backend restriction:** When Grouped GEMM, Alltoall communication overlapping, or FB overlap is enabled, `--transformer-impl transformer_engine` must be set. | ||
| 26 | + | ||
| 25 | When using mcore MoE, the `--moe-token-dispatcher-type alltoall` option is enabled. | 27 | When using mcore MoE, the `--moe-token-dispatcher-type alltoall` option is enabled. |
| 26 | 28 | ||
| 27 | ## Usage | 29 | ## Usage |
| 28 | 30 | ||
| 29 | -Enable the `--moe-permutation-async-comm` parameter. | 31 | +The supported types of `--moe-token-dispatcher-type` are as follows: |
| 30 | 32 | ||
| 31 | -> [!NOTE] | 33 | +| Type | Support | |
| 32 | -> | 34 | +| --- | --- | |
| 33 | -> When `--moe-grouped-gemm` is enabled, expert computation is merged into a single operator, so the computation-communication overlapping optimization becomes ineffective. | 35 | +| `alltoall` | Supported; you can select Alltoall communication overlapping, FB overlap, MC2, or permute fusion according to the constraints. | |
| 36 | +| `allgather` | Supported, and it is the default type; it uses the dedicated [Allgather Configuration](megatron-moe-allgather-dispatcher.md) and does not support dynamic sequence lengths. | | ||
| 37 | +| `flex` (`deepep/hybridep`) | Not supported; NPU adaptation has not been completed yet. | | ||
| 38 | + | ||
| 39 | +Set `--moe-token-dispatcher-type alltoall` to select the Alltoall dispatcher. For the computation-communication overlapping configuration, see [Alltoall Communication Overlapping](megatron-moe-alltoall-overlap-comm.md). | ||
| 40 | + | ||
| 41 | +To use `--moe-alltoall-mc2`, the scenario must be dropless, with `--expert-tensor-parallel-size 1` set and `--moe-expert-capacity-factor` not set. | ||
| 34 | 42 | ||
| 35 | ## Effects | 43 | ## Effects |
| 36 | 44 | ||
| @@ -7,30 +7,30 @@ In MoE, a large amount of EP communication is not overlapped with computation, a | |||
| 7 | ## Solution | 7 | ## Solution |
| 8 | 8 | ||
| 9 | During the forward pass, asynchronous communication is used to overlap with computation as much as possible. Meanwhile, the entire computation graph is partitioned into subgraphs, enabling concurrent communication and computation during the backward pass to accelerate model training. | 9 | During the forward pass, asynchronous communication is used to overlap with computation as much as possible. Meanwhile, the entire computation graph is partitioned into subgraphs, enabling concurrent communication and computation during the backward pass to accelerate model training. |
| 10 | -This feature supports both alltoall dispatchers, with targeted optimizations applied to the two different dispatchers: alltoall and alltoall_seq. | 10 | +This feature currently supports the alltoall dispatcher. |
| 11 | -Additionally, the alltoall branch is compatible with Megatron's moe-shared-expert-overlap and, through finer-grained overlapping, achieves further performance improvements over the native solution. | 11 | +Additionally, the alltoall branch is compatible with Megatron's shared_expert_overlap and, through finer-grained overlapping, achieves further performance improvements over the native solution. |
| 12 | 12 | ||
| 13 | ## Usage | 13 | ## Usage |
| 14 | 14 | ||
| 15 | -Enable this feature by turning on `--moe-alltoall-overlap-comm`. | 15 | +**Backend limitation:** `--transformer-impl transformer_engine` must be set, and `local` is not supported. |
| 16 | 16 | ||
| 17 | -If the branch is `alltoall_seq`, the following must also be enabled: | 17 | +Use the following parameters to enable communication overlap, and set `--expert-model-parallel-size` to greater than 1: |
| 18 | 18 | ||
| 19 | -- `--moe-permutation-async-comm`. | 19 | +```bash |
| 20 | -- `--moe-token-dispatcher-type alltoall_seq`. | 20 | +--moe-alltoall-overlap-comm \ |
| 21 | -- `--moe-grouped-gemm`, currently only supports Grouped MLP. | 21 | +--transformer-impl transformer_engine \ |
| 22 | +--moe-token-dispatcher-type alltoall \ | ||
| 23 | +--moe-grouped-gemm | ||
| 24 | +``` | ||
| 22 | 25 | ||
| 23 | -And when tp>1, you need to also enable | 26 | +- Only `alltoall` is supported; `allgather` and `flex` are not supported. |
| 24 | -`--moe-tp-extend-ep` | 27 | +- `--delay-wgrad-compute`, `--overlap-dispatch-backward-with-experts-wgrad`, and `--overlap-moe-expert-parallel-comm` cannot be enabled at the same time. |
| 25 | - | 28 | +- `--moe-zero-memory` only supports `disable` or `level0`. |
| 26 | -If the branch is the `alltoall` branch, you need to enable: | 29 | +- `--recompute-activation-function` cannot be used together with `--hybrid-layer-pattern`. |
| 27 | - | 30 | +- Supports being enabled together with `--overlap-grad-reduce`. |
| 28 | -- `--moe-token-dispatcher-type alltoall`. | ||
| 29 | -- `--moe-grouped-gemm`, currently only supports Grouped MLP. | ||
| 30 | -- `--moe-tp-extend-ep` is not supported. If you need this feature, switch to `alltoall_seq`. | ||
| 31 | 31 | ||
| 32 | ## Application Scenario | 32 | ## Application Scenario |
| 33 | 33 | ||
| 34 | This feature is suitable for scenarios using the megatron-moe dropless branch where training performance needs to be improved. Compared with the baseline dispatcher scenario, performance can be improved by over 10%. | 34 | This feature is suitable for scenarios using the megatron-moe dropless branch where training performance needs to be improved. Compared with the baseline dispatcher scenario, performance can be improved by over 10%. |
| 35 | After enabling `--moe-shared-expert-overlap`, performance can still be improved by more than 4%. | 35 | After enabling `--moe-shared-expert-overlap`, performance can still be improved by more than 4%. |
| 36 | -Enabling this feature will increase memory usage, which is normal. In this case, you can use the [ZeroMemory feature](megatron-moe-zero-memory.md) to adjust memory usage. | 36 | +Enabling this feature will increase memory usage, which is normal. In this case, you can use the ZeroMemory feature to adjust memory usage. For an introduction to and configuration of ZeroMemory, see [here](megatron-moe-zero-memory.md). |
| @@ -4,9 +4,12 @@ | |||
| 4 | 4 | ||
| 5 | The key bottleneck in MoE model training lies in the high cost of AllToAll (A2A) communication, which significantly impacts training MFU. Additionally, within the same microbatch, A2A communication and computation have dependencies, making A2A communication difficult to overlap. | 5 | The key bottleneck in MoE model training lies in the high cost of AllToAll (A2A) communication, which significantly impacts training MFU. Additionally, within the same microbatch, A2A communication and computation have dependencies, making A2A communication difficult to overlap. |
| 6 | 6 | ||
| 7 | -During the training of the DeepSeek V3 model, the DeepSeek team innovatively proposed bidirectional pipeline AllToAll (A2A) overlap across microbatches, known as the DualPipe algorithm. DualPipe simultaneously inputs microbatches from both ends of the pipeline and incorporates the ZeroBubble concept for dw/dx separation, further reducing pipeline bubbles. Meanwhile, since there are no dependencies between the forward and backward passes of different microbatches, DualPipe orchestrates computation and communication through dual-stream scheduling, achieving full A2A communication overlap in the 1F1B phase. For details, see [DeepSeek-V3 Technical Report](<https://arxiv.org/abs/2412.19437>). | 7 | +During the training of the DeepSeek V3 model, the DeepSeek team innovatively proposed bidirectional pipeline AllToAll (A2A) overlap across microbatches, known as the DualPipe algorithm. |
| 8 | +DualPipe simultaneously inputs microbatches from both ends of the pipeline and incorporates the ZeroBubble concept for dw/dx separation, further reducing pipeline bubbles. | ||
| 9 | +Meanwhile, since there are no dependencies between the forward and backward passes of different microbatches, DualPipe orchestrates computation and communication through dual-stream scheduling, achieving full A2A communication overlap in the 1F1B phase. For details, see | ||
| 10 | + [DeepSeek-V3 Technical Report](https://arxiv.org/abs/2412.19437). | ||
| 8 | 11 | ||
| 9 | -Specifically, the forward computation and communication within a single layer are sequentially split into four stages: Attention(F), Dispatch(F), MLP(F), and Combine(F). The backward computation within a single layer is sequentially split into Combine(B), MLP(B), Dispatch(B), and Attention(B), where Dispatch and Combine are the A2A communication before and after the MLP computation, respectively. By orchestrating the forward and backward computation and communication through dual-stream scheduling, full A2A communication overlap is achieved in the 1F1B phase. The principle is illustrated below (<https://github.com/deepseek-ai/profile-data>). | 12 | +Specifically, the forward computation and communication within a single layer are sequentially split into four stages: Attention(F), Dispatch(F), MLP(F), and Combine(F). The backward computation within a single layer is sequentially split into Combine(B), MLP(B), Dispatch(B), and Attention(B), where Dispatch and Combine are the A2A communication before and after the MLP computation, respectively. By orchestrating the forward and backward computation and communication through dual-stream scheduling, full A2A communication overlap is achieved in the 1F1B phase. The [principle](https://github.com/deepseek-ai/profile-data) is illustrated below. |
| 10 | 13 | ||
| 11 |  | 14 |  |
| 12 | 15 | ||
| @@ -14,25 +17,25 @@ Since the forward and backward computations belong to different microbatches, th | |||
| 14 | 17 | ||
| 15 | ## Solution | 18 | ## Solution |
| 16 | 19 | ||
| 17 | -MindSpeed has designed and implemented a high-performance MoE cross-microbatch A2A communication overlap solution based on the characteristics of Ascend hardware. Through fine-grained computation and communication pipelining, it achieves **50%** A2A communication overlap in the warmup/cooldown phases and **100%** A2A communication overlap in the 1F1B phase. On the DeepSeek V3 model, combined with DualpipeV, it delivers an end-to-end performance improvement of **10%** compared to MindSpeed's existing A2A overlap feature `--moe-alltoall-overlap-comm`. | 20 | +MindSpeed has designed and implemented a high-performance MoE cross-microbatch A2A communication overlap solution based on the characteristics of Ascend hardware. Through fine-grained computation and communication pipelining, it achieves **50**% A2A communication overlap in the warmup/cooldown phases and **100**% A2A communication overlap in the 1F1B phase. On the DeepSeek V3 model, combined with DualpipeV, it delivers an end-to-end performance improvement of **10**% compared to MindSpeed's existing A2A overlap feature `--moe-alltoall-overlap-comm`. |
| 18 | 21 | ||
| 19 | -**Cross-Microbatch A2A Communication Overlap** | 22 | +### Cross-Microbatch A2A Communication Overlap |
| 20 | 23 | ||
| 21 | The fine-grained computation and communication pipeline orchestration for the 1F1B phase implemented by MindSpeed is illustrated below: | 24 | The fine-grained computation and communication pipeline orchestration for the 1F1B phase implemented by MindSpeed is illustrated below: |
| 22 |  | 25 |  |
| 23 | - | ||
| 24 | By decoupling the dw and dx computations for the dispatch experts and the Attention backward pass, full A2A overlap can be achieved during the 1F1B phase. Additionally, since communication operations on Ascend hardware are issued by the AICPU and do not consume cube computation unit resources, the concurrency of computation and communication has minimal impact on computational efficiency. Furthermore, the dw computation of the Attention component is used to overlap PP communication, thereby achieving full communication overlap during the 1F1B phase. | 26 | By decoupling the dw and dx computations for the dispatch experts and the Attention backward pass, full A2A overlap can be achieved during the 1F1B phase. Additionally, since communication operations on Ascend hardware are issued by the AICPU and do not consume cube computation unit resources, the concurrency of computation and communication has minimal impact on computational efficiency. Furthermore, the dw computation of the Attention component is used to overlap PP communication, thereby achieving full communication overlap during the 1F1B phase. |
| 25 | 27 | ||
| 26 | -The following diagram shows a profiling illustration of A2A communication overlap within a single layer when this feature is used with DeepSeek-V3-671B. | 28 | +The following diagram shows a profiling illustration of A2A communication overlap within a single layer when this feature is used with the real 671B DeepSeekV3 model. |
| 29 | + | ||
| 27 |  | 30 |  |
| 28 | 31 | ||
| 29 | With this feature enabled, the four A2A communication operations in the 1F1B phase can be completely overlapped by computation. | 32 | With this feature enabled, the four A2A communication operations in the 1F1B phase can be completely overlapped by computation. |
| 30 | 33 | ||
| 31 | -**A2A Self-Overlap in Warmup/Cooldown Phases** | 34 | +### A2A Self-Overlap in Warmup/Cooldown Phases |
| 32 | 35 | ||
| 33 | During the pipeline warmup/cooldown phase, only forward/backward computations of the same microbatch exist, so the cross-microbatch A2A communication overlap method cannot be used. To further increase the overlap ratio, intra-layer self-overlap is used during the warmup and cooldown phases: the forward computation of shared experts overlaps dispatch communication, the backward computation of shared experts overlaps combine communication, and the dw computation of routed experts overlaps dispatch communication. | 36 | During the pipeline warmup/cooldown phase, only forward/backward computations of the same microbatch exist, so the cross-microbatch A2A communication overlap method cannot be used. To further increase the overlap ratio, intra-layer self-overlap is used during the warmup and cooldown phases: the forward computation of shared experts overlaps dispatch communication, the backward computation of shared experts overlaps combine communication, and the dw computation of routed experts overlaps dispatch communication. |
| 34 | 37 | ||
| 35 | -**Cross-Microbatch A2A Communication Overlap Based on DualPipeV and Megatron VPP** | 38 | +### Cross-Microbatch A2A Communication Overlap Based on DualpipeV and Megatron VPP |
| 36 | 39 | ||
| 37 | MindSpeed implements MoE cross-microbatch A2A communication overlap based on DualPipe. For details, see [DualPipeV Introduction](../dualpipev.md). | 40 | MindSpeed implements MoE cross-microbatch A2A communication overlap based on DualPipe. For details, see [DualPipeV Introduction](../dualpipev.md). |
| 38 | 41 | ||
| @@ -44,28 +47,27 @@ The middle red-boxed section can utilize cross-microbatch A2A overlap. Compared | |||
| 44 | 47 | ||
| 45 | ## Usage | 48 | ## Usage |
| 46 | 49 | ||
| 50 | +**Backend limitation:** `--transformer-impl transformer_engine` must be set, and `local` is not supported. | ||
| 51 | + | ||
| 47 | Please note that this feature has currently only been validated in the DeepSeek V3 scenario. Further validation and adaptation are required for other MoE model scenarios. | 52 | Please note that this feature has currently only been validated in the DeepSeek V3 scenario. Further validation and adaptation are required for other MoE model scenarios. |
| 48 | 53 | ||
| 49 | -- Add `--moe-fb-overlap` to the launch script. | 54 | +1. Add `--moe-fb-overlap` to the launch script, and set `--transformer-impl transformer_engine` and `--expert-model-parallel-size` greater than 1. |
| 50 | -- If you need to use the DualPipeV pipeline, add `--schedules-method dualpipev` to the launch script. | 55 | + |
| 51 | -- If using Megatron VPP, configure `--num-layers-per-virtual-pipeline-stage` in the launch script. | 56 | +2. If you need to use the DualpipeV pipeline, add `--schedules-method dualpipev` to the launch script. |
| 52 | -- Non-PP, multi-microbatch scenarios are supported. Do not configure `--pipeline-model-parallel-size` in the launch script, or set `--pipeline-model-parallel-size 1`. | 57 | +3. If using Megatron VPP, configure `--num-layers-per-virtual-pipeline-stage` in the launch script. |
| 58 | +4. Non-PP, multi-microbatch scenarios are supported. Do not configure `--pipeline-model-parallel-size` in the launch script, or set `--pipeline-model-parallel-size 1`. | ||
| 59 | +5. `--moe-unperm2-mem-optim-swap` can be used to swap out the unpermute intermediate results. | ||
| 53 | 60 | ||
| 54 | ## Usage Constraints | 61 | ## Usage Constraints |
| 55 | 62 | ||
| 56 | -- Only `--moe-token-dispatcher-type=alltoall` is supported. The `allgather/alltoall_seq` dispatcher is not yet supported. | 63 | +1. Currently only `--moe-token-dispatcher-type=alltoall` is supported; the `allgather/flex` dispatcher is not supported. |
| 57 | -- Using `--swap-attention` simultaneously is not recommended, as it causes performance degradation. | 64 | +2. Currently `--expert-tensor-parallel-size=1` must be set, and expert TP is not yet supported. |
| 58 | -- `--expert-tensor-parallel-size=1` must be set, and expert TP is not yet supported. | 65 | +3. The Megatron MoE Token Drop&Pad mode is not yet supported; Dropless and Drop modes are supported. |
| 59 | -- The Megatron MoE Token Drop & Pad mode is not supported. Dropless and Drop modes are supported. | 66 | +4. This currently depends on GroupedMatmul. Ensure that `--moe-grouped-gemm` is enabled. |
| 60 | -- This depends on GroupedMatmul. Ensure that `--moe-grouped-gemm` is enabled. | 67 | +5. `--moe-zero-memory` supports `disable` (default) or `level0`. |
| 61 | -- Only `--moe-zero-memory=level0` is supported, and the `moe-zero-memory-num-layers` configuration is not supported. | 68 | +6. Asynchronous DP communication overlap is not yet supported, and `--overlap-grad-reduce` must be disabled. |
| 62 | -- Asynchronous DP communication overlap is not supported, and `--overlap-grad-reduce` must be disabled. | 69 | +7. A custom `--pipeline-model-parallel-layout` does not allow empty decoder chunks. |
| 63 | -- only Mcore models are supported. Do not enable `--use_legacy_models`. | 70 | +8. Under the VPP pipeline, the following additional constraints apply: |
| 64 | -- Under VPP pipeline, the following additional constraints apply: | 71 | + - `GBS // (MBS * PP * DP) > 1` |
| 65 | - - GBS > 1 \* DP \* PP \* MBS | ||
| 66 | - If noop layers are used, they must be added to the last VPP stage at the end of the model. | 72 | - If noop layers are used, they must be added to the last VPP stage at the end of the model. |
| 67 | -- Conflicts with the following features and cannot be used simultaneously: | 73 | +9. It cannot be used together with `--delay-wgrad-compute`. |
| 68 | - - `moe-alltoall-overlap-comm` | ||
| 69 | - - `moe-hierarchical-alltoallv` | ||
| 70 | - - `recompute-in-advance` | ||
| 71 | - - `recompute-in-bubble` | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +# MoE Fixed Router | ||
| 2 | + | ||
| 3 | +Assigns experts through a deterministic round-robin rule, for MoE training configurations with fixed routing. | ||
| 4 | + | ||
| 5 | +## Usage | ||
| 6 | + | ||
| 7 | +Add `--fix-router`. Disabled by default. `--expert-model-parallel-size` must be greater than 1, and `--moe-router-fusion` cannot be enabled at the same time. | ||
| @@ -10,7 +10,13 @@ By calling the gmm fused operator, multiple expert computations are fused to ach | |||
| 10 | 10 | ||
| 11 | ## Usage | 11 | ## Usage |
| 12 | 12 | ||
| 13 | -Set `--moe-grouped-gemm`: enables Grouped GEMM computation. Support MoE allgather, alltoall, and alltoall_seq dispatchers. | 13 | +**Backend limitation:** `--transformer-impl transformer_engine` must be set; `local` is not supported. |
| 14 | + | ||
| 15 | +Set `--transformer-impl transformer_engine --moe-grouped-gemm` to enable Grouped GEMM using TEGroupedMLP; supports `allgather` and `alltoall` dispatchers; does not support the `local` backend or `flex`, which has not yet completed NPU adaptation. | ||
| 16 | + | ||
| 17 | +`--te-gmm-mode` defaults to `compatible`; when `performance` is selected, packed grouped weight is used. | ||
| 18 | + | ||
| 19 | +`--gmm-gradient-accumulation-fusion` (alias `--gemm-gradient-accumulation-fusion`) independently controls expert gradient accumulation fusion. | ||
| 14 | 20 | ||
| 15 | ## Effects | 21 | ## Effects |
| 16 | 22 | ||
| @@ -19,9 +25,9 @@ Typical scenarios: | |||
| 19 | - Scenarios where a smaller EP leads to more experts per device, and DeepSeek MoE has a large number of experts. | 25 | - Scenarios where a smaller EP leads to more experts per device, and DeepSeek MoE has a large number of experts. |
| 20 | - Single small DeepSeek MoE fine-grained expert, FFN scale not large, and larger TP leading to smaller per-card shard computation. | 26 | - Single small DeepSeek MoE fine-grained expert, FFN scale not large, and larger TP leading to smaller per-card shard computation. |
| 21 | 27 | ||
| 22 | -- As the FFN scale increases, computation is no longer fragmented, single-expert computation efficiency improves, and the benefit of Grouped GEMM diminishes. | 28 | +1. As the FFN scale increases, computation is no longer fragmented, single-expert computation efficiency improves, and the benefit of Grouped GEMM diminishes. |
| 23 | 29 | ||
| 24 | - **Table 1**: Grok model FFN size and performance acceleration comparison | 30 | + Table 1: Grok model FFN size and performance acceleration comparison |
| 25 | 31 | ||
| 26 | |ffn_hidden_size| 32768 | 16384| 8192| 4096| | 32 | |ffn_hidden_size| 32768 | 16384| 8192| 4096| |
| 27 | |--|--|--|--|--| | 33 | |--|--|--|--|--| |
| @@ -29,9 +35,9 @@ Typical scenarios: | |||
| 29 | |GEMM|2416|1719|1448|1331| | 35 | |GEMM|2416|1719|1448|1331| |
| 30 | |Performance improvement|-5.30%|3.53%|6.12%|8.60%| | 36 | |Performance improvement|-5.30%|3.53%|6.12%|8.60%| |
| 31 | 37 | ||
| 32 | -- The larger the TP and the smaller the EP, the greater the benefit. | 38 | +2. The larger the TP and the smaller the EP, the greater the benefit. |
| 33 | - | 39 | + |
| 34 | - **Table 2**: Performance gains for different Mixtral 8x7B model configurations | 40 | + Table 2: Performance gains for different Mixtral 8x7B model configurations |
| 35 | 41 | ||
| 36 | | Configuration | tp4 ep2 16expert | tp4 ep2 8expert | tp2 ep4 16expert | tp2 ep4 8expert | | 42 | | Configuration | tp4 ep2 16expert | tp4 ep2 8expert | tp2 ep4 16expert | tp2 ep4 8expert | |
| 37 | |--|--|--|--|--| | 43 | |--|--|--|--|--| |
| @@ -39,27 +45,30 @@ Typical scenarios: | |||
| 39 | | GEMM | 19415 | 17361 | 11049 | 14290 | | 45 | | GEMM | 19415 | 17361 | 11049 | 14290 | |
| 40 | | Performance gain | 44.06% | 17.93% | 8.39% | -2.19% | | 46 | | Performance gain | 44.06% | 17.93% | 8.39% | -2.19% | |
| 41 | 47 | ||
| 42 | -> [!NOTE] | 48 | +## Notes |
| 43 | -> | ||
| 44 | -> Megatron does not natively support using `--moe-grouped-gemm` when `--bf16` is enabled. | ||
| 45 | -> When Grouped GEMM computation is enabled via the `--moe-grouped-gemm` parameter, the npu_gmm fused operator is invoked. | ||
| 46 | 49 | ||
| 47 | -**Operator Input and Output** | 50 | +1. TEGroupedMLP supports `--bf16`; gradient accumulation fusion requires BF16 or FP16 and cannot be used together with FP8/FP4. |
| 51 | +2. When Grouped GEMM computation is enabled via the `--moe-grouped-gemm` parameter, the npu_gmm fused operator is invoked. | ||
| 52 | + | ||
| 53 | +The operator input and output formats are as follows: | ||
| 48 | 54 | ||
| 49 | ```python | 55 | ```python |
| 50 | y = npu_gmm(x, weight, bias=None, group_list=None, group_type=0, gemm_fusion=False, original_weight=None) | 56 | y = npu_gmm(x, weight, bias=None, group_list=None, group_type=0, gemm_fusion=False, original_weight=None) |
| 51 | ``` | 57 | ``` |
| 52 | 58 | ||
| 53 | -- Input: | 59 | +Input: |
| 54 | - - x: Required input; a tensor; data type: float16, bfloat16, float32 | 60 | + |
| 55 | - - weight: Required input; a tensor; data type: float16, bfloat16, float32 | 61 | +- x: Required input; a tensor; data type: float16, bfloat16, float32 |
| 56 | - - bias: Optional input; a tensor; data type: float16, float32; default value: None. In training scenarios, only bias=None is supported. | 62 | +- weight: Required input; a tensor; data type: float16, bfloat16, float32 |
| 57 | - - group_list: optional input; a tensor; data type: list[int64]; default value: None. | 63 | +- bias: Optional input; a tensor; data type: float16, float32; default value: None. In training scenarios, only bias=None is supported. |
| 58 | - - group_type: optional input; data type: int64; representing the axis to be grouped. For example, if matrix multiplication is C[m,n]=A[m,k]xB[k,n], then group_type values are -1: no grouping, 0: m-axis grouping, 1: n-axis grouping, 2: k-axis grouping. Default value: 0. | 64 | +- group_list: optional input; data type: list[int64], tensor; default value: None. |
| 59 | - - gemm_fusion: optional input; data type: bool; value: True, False. Used to enable the GMM+ADD fused operator when accumulating gradients in the backward pass. Default value: False. | 65 | +- group_type: optional input; data type: int64; representing the axis to be grouped. For example, if matrix multiplication is C[m,n]=A[m,k]xB[k,n], then group_type values are -1: no grouping, 0: m-axis grouping, 1: n-axis grouping, 2: k-axis grouping. Default value: 0. |
| 60 | - - original_weight: optional input; a tensor; data type: float16, bfloat16, float32. Used to obtain the main_grad of the weight before view for gradient accumulation in GMM+ADD; Default value: None. | 66 | +- gemm_fusion: optional input; data type: bool; value: True, False. Used to enable the GMM+ADD fused operator when accumulating gradients in the backward pass. Default value: False. |
| 61 | -- Output: | 67 | +- original_weight: optional input; a tensor; data type: float16, bfloat16, float32. Used to obtain the main_grad of the weight before view for gradient accumulation in GMM+ADD; Default value: None. |
| 62 | - - y: required output; data type: float16, bfloat16, float32 | 68 | + |
| 69 | +Output: | ||
| 70 | + | ||
| 71 | +- y: required output; data type: float16, bfloat16, float32 | ||
| 63 | 72 | ||
| 64 | In non-quantized scenarios, this operator only supports the following combinations of input and output types. Specifying unsupported types for parameters may cause operator errors and affect training efficiency: | 73 | In non-quantized scenarios, this operator only supports the following combinations of input and output types. Specifying unsupported types for parameters may cause operator errors and affect training efficiency: |
| 65 | 74 | ||
| @@ -1,30 +0,0 @@ | |||
| 1 | -# Megatron MoE TP Extended EP | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -When TP+EP is enabled, the expert layer TP group partitions expert parameters. In fine-grained small expert scenarios of MoE, the GMM operator efficiency drops significantly after TP partitioning. | ||
| 6 | - | ||
| 7 | -## Solution | ||
| 8 | - | ||
| 9 | -To address the GMM operator efficiency degradation after TP partitioning in small expert scenarios, the expert layer TP group does not partition expert parameters but instead partitions the number of experts. | ||
| 10 | - | ||
| 11 | -## Use Cases | ||
| 12 | - | ||
| 13 | -Fine-grained small experts, similar to DeepSeek-V2 models, where each expert has a small number of parameters. | ||
| 14 | - | ||
| 15 | -## Usage | ||
| 16 | - | ||
| 17 | -- Enable `--moe-tp-extend-ep` to use this feature. | ||
| 18 | -- The following must also be enabled: | ||
| 19 | - - `--moe-permutation-async-comm` | ||
| 20 | - -`--moe-grouped-gemm`, currently only supports Grouped MLP. | ||
| 21 | -- Configuration constraint: Ensure that `--num-experts` is divisible by the product of `--tensor-model-parallel-size` and `--expert-model-parallel-size`. | ||
| 22 | - | ||
| 23 | -> [!NOTE] | ||
| 24 | -> | ||
| 25 | -> - Currently, this feature does not support the `Moe Token drop and pad` mode, meaning `--moe-expert-capacity-factor` must be `None`. | ||
| 26 | -> - Currently, only the `alltoall_seq dispatcher` is supported. | ||
| 27 | - | ||
| 28 | -## Performance | ||
| 29 | - | ||
| 30 | -By avoiding TP splitting of expert parameters, the GMM operator efficiency is improved in small expert scenarios, thereby enhancing the overall model training performance. For MoE models at the trillion-parameter scale similar to DeepSeek-V2 with fine-grained small experts, the performance can be improved by over 10%. | ||
| @@ -7,30 +7,21 @@ The dynamic memory in MoE is relatively large. After using the overlap strategy, | |||
| 7 | ## Solution | 7 | ## Solution |
| 8 | 8 | ||
| 9 | For this scenario, we use communication-heavy strategies, fine-grained recomputation, and targeted swapping to save memory, employing computation to hide the communication-heavy operations and swapping, and hiding recomputation with uncovered communication. | 9 | For this scenario, we use communication-heavy strategies, fine-grained recomputation, and targeted swapping to save memory, employing computation to hide the communication-heavy operations and swapping, and hiding recomputation with uncovered communication. |
| 10 | -Supports `alltoall` and `alltoall_seq` dispatchers. | 10 | +Currently supports the `alltoall` dispatcher. |
| 11 | 11 | ||
| 12 | -- level0 performs recomputation in the expert computation part, with relatively small performance loss. level1 performs recomputation to a greater extent, with relatively more performance loss than level0. The memory saved is 70%+ and 90%+ of the memory that can be saved by recomputing the MLP, respectively, and the speed is better than recomputing the MLP. | 12 | +- level0 performs recomputation in the expert computation part. |
| 13 | - The MLP here also includes the shared expert part. | 13 | - The MLP here also includes the shared expert part. |
| 14 | - In the `alltoall` branch, the probs recomputation is moved forward to further improve memory savings. | 14 | - In the `alltoall` branch, the probs recomputation is moved forward to further improve memory savings. |
| 15 | 15 | ||
| 16 | ## Usage | 16 | ## Usage |
| 17 | 17 | ||
| 18 | -Enable this feature by setting: | 18 | +**Backend limitation:** `--transformer-impl transformer_engine` must be set, and `local` is not supported. |
| 19 | -`--moe-zero-memory level0` or `--moe-zero-memory level1` | ||
| 20 | 19 | ||
| 21 | -The following must also be enabled: | 20 | +Set `--moe-zero-memory level0` and enable `--moe-alltoall-overlap-comm` or `--moe-fb-overlap`. This optimization applies to all MoE layers. |
| 22 | 21 | ||
| 23 | -- `--moe-alltoall-overlap-comm` or `--moe-fb-overlap` | 22 | +- When using `--moe-fb-overlap`, the [FB overlap usage constraints](megatron-moe-fb-overlap.md#usage-constraints) must be satisfied. |
| 24 | -- If used with `--moe-fb-overlap`, refer to [AlltoAll Communication Overlap Across Microbatches in MoE](megatron-moe-fb-overlap.md). | 23 | +- `level0` cannot be used together with `--moe-apply-probs-on-input` or `--moe-latent-size`. |
| 25 | - | ||
| 26 | -Parameters: | ||
| 27 | - | ||
| 28 | -- For `--moe-zero-memory level0`, since the performance loss is relatively small, layer count configuration is not supported. The feature is enabled for all layers. | ||
| 29 | - | ||
| 30 | -- For `--moe-zero-memory level1`, all layers are enabled by default. You can also configure the number of layers to apply memory optimization using `--moe-zero-memory-num-layers x`, where `x` is the number of layers. The value of x should be greater than or equal to 0 and less than or equal to the total number of model layers (`num_layers//pp`). | ||
| 31 | 24 | ||
| 32 | ## Applicable Scenarios | 25 | ## Applicable Scenarios |
| 33 | 26 | ||
| 34 | -1. Currently supports `alltoall` and `alltoall_seq` dispatcher modes, suitable for scenarios where megatron-moe requires recomputation. | 27 | +Applicable to MoE `alltoall` dispatcher scenarios that require recomputation. |
| 35 | -2. Supports enabling `level0` when `moe-fb-overlap` is active. | ||
| 36 | -3. The `moe-zero-memory-num-layers` configuration is not supported when `--moe-fb-overlap` is enabled. | ||
| @@ -3,12 +3,10 @@ | |||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | In the MoE architecture, the MoEAlltoAllTokenDispatcher scheduler is responsible for assigning tokens to various experts for processing and then reassembling the processed results back into the original token order. This process typically involves the following steps: | 5 | In the MoE architecture, the MoEAlltoAllTokenDispatcher scheduler is responsible for assigning tokens to various experts for processing and then reassembling the processed results back into the original token order. This process typically involves the following steps: |
| 6 | - | 6 | +Token routing: determining which expert should process each token. This is accomplished through an expert gating mechanism, which selects the most suitable expert for each token. |
| 7 | -- Token routing: determining which expert should process each token. This is accomplished through an expert gating mechanism, which selects the most suitable expert for each token. | 7 | +Data rearrangement (Permute): grouping tokens by their selected experts so that each expert can process its assigned tokens in parallel. This typically involves permuting the tokens. |
| 8 | -- Data rearrangement (Permute): grouping tokens by their selected experts so that each expert can process its assigned tokens in parallel. This typically involves permuting the tokens. | 8 | +Expert processing: each expert processes its assigned tokens in parallel. |
| 9 | -- Expert processing: each expert processes its assigned tokens in parallel. | 9 | +Result reassembly (Unpermute): after processing is complete, the results from different experts need to be reassembled back into the original token order. |
| 10 | -- Result reassembly (Unpermute): after processing is complete, the results from different experts need to be reassembled back into the original token order. | ||
| 11 | - | ||
| 12 | In the above workflow, the data rearrangement and result reassembly steps are among the performance bottlenecks. This is because these two steps involve significant data movement, especially when using distributed training. | 10 | In the above workflow, the data rearrangement and result reassembly steps are among the performance bottlenecks. This is because these two steps involve significant data movement, especially when using distributed training. |
| 13 | 11 | ||
| 14 | ## Solution | 12 | ## Solution |
| @@ -17,17 +15,17 @@ To optimize this process, MindSpeed fuses the MoE Token Permute and Unpermute op | |||
| 17 | 15 | ||
| 18 | ## Usage | 16 | ## Usage |
| 19 | 17 | ||
| 18 | +**Backend restriction:** When combined with Grouped GEMM or MoE communication overlapping, `--transformer-impl transformer_engine` must be set. | ||
| 19 | + | ||
| 20 | 1. Add `--moe-permute-fusion` or `--use-fused-moe-token-permute-and-unpermute` to the launch script. Both are equivalent, but `--moe-permute-fusion` is recommended as the preferred option. | 20 | 1. Add `--moe-permute-fusion` or `--use-fused-moe-token-permute-and-unpermute` to the launch script. Both are equivalent, but `--moe-permute-fusion` is recommended as the preferred option. |
| 21 | 2. The following configuration is recommended for optimal performance; otherwise, enabling this fused operator may degrade performance in certain scenarios. | 21 | 2. The following configuration is recommended for optimal performance; otherwise, enabling this fused operator may degrade performance in certain scenarios. |
| 22 | - | 22 | +Set `--moe-token-dispatcher-type alltoall --expert-tensor-parallel-size 1`. |
| 23 | -- When `--moe-token-dispatcher-type alltoall` is set, configure `--expert-tensor-parallel-size 1`. | ||
| 24 | -- When `--moe-token-dispatcher-type alltoall_seq` is set, enable `--moe-tp-extend-ep`. | ||
| 25 | 23 | ||
| 26 | ## Usage Constraints | 24 | ## Usage Constraints |
| 27 | 25 | ||
| 28 | -1. Supported dispatcher types: Currently, only `--moe-token-dispatcher-type alltoall` and `--moe-token-dispatcher-type alltoall_seq` are supported. `--moe-token-dispatcher-type allgather` is not yet supported. | 26 | +1. Only `--moe-token-dispatcher-type alltoall` is supported; allgather, flex, and `--moe-router-padding-for-quantization` are not supported. |
| 29 | 2. Compatibility between the fusion operator and expert capacity parameters: To enable `--moe-expert-capacity-factor`, `--moe-pad-expert-input-to-capacity` must also be enabled for compatibility with the fusion operator. If only `--moe-expert-capacity-factor` is enabled without `--moe-pad-expert-input-to-capacity`, the fusion operator is not yet compatible. | 27 | 2. Compatibility between the fusion operator and expert capacity parameters: To enable `--moe-expert-capacity-factor`, `--moe-pad-expert-input-to-capacity` must also be enabled for compatibility with the fusion operator. If only `--moe-expert-capacity-factor` is enabled without `--moe-pad-expert-input-to-capacity`, the fusion operator is not yet compatible. |
| 30 | -3. System environment requirements: Limited to system environments with version identifiers `CANN 8.3.RC1` / `TorchNPU 7.2.RC1` and all subsequent iterative versions. | 28 | +3. System environment requirements: Limited to system environments with version identifiers `CANN 8.3.RC1` / `PTA 7.2.RC1` and all subsequent iterative versions. |
| 31 | 29 | ||
| 32 | ## Effects | 30 | ## Effects |
| 33 | 31 | ||
| @@ -3,6 +3,7 @@ | |||
| 3 | ## Background and Challenges | 3 | ## Background and Challenges |
| 4 | 4 | ||
| 5 | During MoE model training, expert load exhibits an imbalance phenomenon, especially in the pre-training phase. The number of tokens processed by experts on different devices varies significantly, and the load changes drastically, causing fast-slow device issues that degrade throughput. | 5 | During MoE model training, expert load exhibits an imbalance phenomenon, especially in the pre-training phase. The number of tokens processed by experts on different devices varies significantly, and the load changes drastically, causing fast-slow device issues that degrade throughput. |
| 6 | +The load on local training devices is shown in the figure below, and the load in large-scale training is similar. | ||
| 6 | 7 | ||
| 7 | ## Solution | 8 | ## Solution |
| 8 | 9 | ||
| @@ -11,30 +12,29 @@ To address the above issues, a load balancing solution based on expert migration | |||
| 11 | <p align="center"> <img src="../figures/expert_load_balance1_en.png" ></p> | 12 | <p align="center"> <img src="../figures/expert_load_balance1_en.png" ></p> |
| 12 | 13 | ||
| 13 | The solution mainly consists of two parts: the planner and the executor. | 14 | The solution mainly consists of two parts: the planner and the executor. |
| 14 | - | ||
| 15 | **Planner**: Performs migration preparation tasks, including expert load data collection, load prediction, and expert placement optimization. | 15 | **Planner**: Performs migration preparation tasks, including expert load data collection, load prediction, and expert placement optimization. |
| 16 | 16 | ||
| 17 | * The expert load data collection functionality is integrated within the load prediction module. | 17 | * The expert load data collection functionality is integrated within the load prediction module. |
| 18 | * Expert load prediction uses the Exponential Moving Average (EMA) method, with the calculation formula: | 18 | * Expert load prediction uses the Exponential Moving Average (EMA) method, with the calculation formula: |
| 19 | -$ELP_{t+1} = \theta * ELP_{t} + (1-\theta)EL_t$ | 19 | +$ELP_{t+1} = \theta * ELP_{t} + (1-\theta)EL_t, $ |
| 20 | -where $ELP_t$ is the expert load prediction at step $t$, $EL_t$ is the collected expert load data at step $t$, and $θ$ is the EMA weight, typically ranging from 0.9 to 0.999. A larger $θ$ means the load prediction focuses more on historical data, with less influence from the current load data. In this solution, θ=0.9 is used. Compared to larger θ values, the current load data is given higher weight, enabling better capture of current load characteristics. As a result, the expert migration based on this approach adapts more effectively to changing loads. | 20 | +where $ELP_t$ is the expert load prediction at step $t$, $EL_t$ is the collected expert load data at step $t$, and $θ$ is the EMA weight, typically ranging from 0.9 to 0.999. A larger $θ$ means the load prediction focuses more on historical data, with less influence from the current load data. In this solution, θ=0.9 is used, enabling better capture of current load characteristics. As a result, the expert migration based on this approach adapts more effectively to changing loads. |
| 21 | The EMA-based load prediction update processes data iteratively, eliminating the need to store historical load information. It is computationally lightweight and delivers excellent prediction results. | 21 | The EMA-based load prediction update processes data iteratively, eliminating the need to store historical load information. It is computationally lightweight and delivers excellent prediction results. |
| 22 | 22 | ||
| 23 | Before migration, an allreduce operation is performed on the expert load prediction results in the DP domain to ensure that all DP domain load predictions and the expert placement mapping based on these predictions are consistent. | 23 | Before migration, an allreduce operation is performed on the expert load prediction results in the DP domain to ensure that all DP domain load predictions and the expert placement mapping based on these predictions are consistent. |
| 24 | 24 | ||
| 25 | The expert placement optimization adopts a greedy algorithm, with the main steps as follows: | 25 | The expert placement optimization adopts a greedy algorithm, with the main steps as follows: |
| 26 | 26 | ||
| 27 | -1. Initialization: the number of experts on each device is 0, and the number of processed tokens is 0. | 27 | +   (1) Initialization: the number of experts on each device is 0, and the number of processed tokens is 0. |
| 28 | 28 | ||
| 29 | -2. Based on the expert load prediction results, find the expert with the highest load in the expert set. | 29 | +   (2) Based on the expert load prediction results, find the expert with the highest load in the expert set. |
| 30 | 30 | ||
| 31 | -3. Traverse each device to find the device with the number of experts less than the preset value and the minimum number of processed tokens. | 31 | +  (3) Traverse each device to find the device with the number of experts less than the preset value and the minimum number of processed tokens. |
| 32 | 32 | ||
| 33 | -4. Assign the expert with the highest load to the device identified in the previous step, and remove this expert from the expert set. | 33 | +  (4) Assign the expert with the highest load to the device identified in the previous step, and remove this expert from the expert set. |
| 34 | 34 | ||
| 35 | -5. Repeat step 2 until all experts have been placed. | 35 | +  (5) Repeat step 2 until all experts have been placed. |
| 36 | 36 | ||
| 37 | -**Executor**: Based on the expert placement mapping provided by the planner, the executor performs expert migration operations, exchanging expert parameters and corresponding optimizer states between devices, while remapping the top-k expert IDs determined by the MoE router to achieve device-level load balancing. | 37 | +***Executor***: Based on the expert placement mapping provided by the planner, the executor performs expert migration operations, exchanging expert parameters and corresponding optimizer states between devices, while remapping the top-k expert IDs determined by the MoE router to achieve device-level load balancing. |
| 38 | The executor consists of two parts: a fine-grained hierarchical expert migration controller and the expert migration operation itself. | 38 | The executor consists of two parts: a fine-grained hierarchical expert migration controller and the expert migration operation itself. |
| 39 | 39 | ||
| 40 | * The controller decides whether to trigger expert migration operations in each transformer layer by detecting whether expert migration can significantly reduce the level of load imbalance. The load imbalance metric is designed as the coefficient of variation of the predicted load, which is the ratio of the standard deviation to the mean. This metric is dimensionless and universally applicable. In this solution, a reduction of the coefficient of variation by at least 0.08 is used as the criterion for whether expert migration is effective. By introducing the controller, MoE layers with a low degree of load imbalance will not undergo expert migration, which reduces migration overhead. This is especially effective during the SFT stage, where the load is relatively stable. | 40 | * The controller decides whether to trigger expert migration operations in each transformer layer by detecting whether expert migration can significantly reduce the level of load imbalance. The load imbalance metric is designed as the coefficient of variation of the predicted load, which is the ratio of the standard deviation to the mean. This metric is dimensionless and universally applicable. In this solution, a reduction of the coefficient of variation by at least 0.08 is used as the criterion for whether expert migration is effective. By introducing the controller, MoE layers with a low degree of load imbalance will not undergo expert migration, which reduces migration overhead. This is especially effective during the SFT stage, where the load is relatively stable. |
| @@ -51,19 +51,19 @@ Perform the following operations on the master parameters and first/second-order | |||
| 51 | ```txt | 51 | ```txt |
| 52 | For buffer in buffers: | 52 | For buffer in buffers: |
| 53 | For bucket in buffer.buckets: | 53 | For bucket in buffer.buckets: |
| 54 | - 1. Allocate buffer: Create an optimizer state exchange buffer with the same capacity as the bucket. | 54 | + 1. Allocate buffer: Create an optimizer state exchange buffer with the same capacity as the bucket. |
| 55 | - 2. Write local states: Slice the local optimizer states of parameters in the bucket and copy them into the exchange buffer. | 55 | + 2. Write local states: Slice the local optimizer states of parameters in the bucket and copy them into the exchange buffer. |
| 56 | - 3. Perform all-gather: Execute an all-gather operation within the data parallel (DP) group on the exchange buffer to obtain the complete optimizer states. | 56 | + 3. Perform all-gather: Execute an all-gather operation within the data parallel (DP) group on the exchange buffer to obtain the complete optimizer states. |
| 57 | - 4. Perform all-to-all: Extract the local expert parameter states from the exchange buffer and migrate experts via an all-to-all operation. | 57 | + 4. Perform all-to-all: Extract the local expert parameter states from the exchange buffer and migrate experts via an all-to-all operation. |
| 58 | - 5. Update local states: Retain the expert parameter state slices in the exchange buffer and update the corresponding local optimizer state slices. | 58 | + 5. Update local states: Retain the expert parameter state slices in the exchange buffer and update the corresponding local optimizer state slices. |
| 59 | - 6. Release buffer: Free the temporarily allocated exchange buffer to conserve memory resources. | 59 | + 6. Release buffer: Release the temporarily allocated exchange buffer. |
| 60 | ``` | 60 | ``` |
| 61 | 61 | ||
| 62 | ## Usage Instructions | 62 | ## Usage Instructions |
| 63 | 63 | ||
| 64 | ### 1. Parameter Configuration | 64 | ### 1. Parameter Configuration |
| 65 | 65 | ||
| 66 | -```yaml | 66 | +```bash |
| 67 | enable_expert_placement: True # Expert migration feature switch | 67 | enable_expert_placement: True # Expert migration feature switch |
| 68 | enable_fine_grained_expert_placement: True # Fine-grained hierarchical expert migration switch. If false, all MoE layers migrate at a fixed frequency by default | 68 | enable_fine_grained_expert_placement: True # Fine-grained hierarchical expert migration switch. If false, all MoE layers migrate at a fixed frequency by default |
| 69 | expert_placement_freq: 50 # Expert migration frequency | 69 | expert_placement_freq: 50 # Expert migration frequency |
| @@ -9,29 +9,34 @@ Traditional Transformer models typically use the multi-head attention (MHA) mech | |||
| 9 | Unlike the traditional KV cache, MLA does not directly store the complete key and value matrices. Instead, it represents keys and values through a compressed latent vector, reducing the KV cache via low-rank compression techniques. During training, the query also undergoes low-rank compression to reduce activation memory. The following figure compares the working mechanisms of MLA with MHA, Grouped-Query Attention (GQA), and Multi-Query Attention (MQA). | 9 | Unlike the traditional KV cache, MLA does not directly store the complete key and value matrices. Instead, it represents keys and values through a compressed latent vector, reducing the KV cache via low-rank compression techniques. During training, the query also undergoes low-rank compression to reduce activation memory. The following figure compares the working mechanisms of MLA with MHA, Grouped-Query Attention (GQA), and Multi-Query Attention (MQA). |
| 10 |  | 10 |  |
| 11 | 11 | ||
| 12 | -For more details on MLA, see the paper [DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model](<https://arxiv.org/abs/2405.04434>). | 12 | +For more details on MLA, see the original paper: |
| 13 | +> DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (<https://arxiv.org/abs/2405.04434>) | ||
| 13 | 14 | ||
| 14 | ## Application Scenario | 15 | ## Application Scenario |
| 15 | 16 | ||
| 17 | +**Backend limitation:** When CP>1, `--transformer-impl transformer_engine` must be set. | ||
| 18 | + | ||
| 16 | MLA addresses the memory bottleneck of standard Transformer models. It can be used as a general model architecture to reduce memory usage and improve inference efficiency. | 19 | MLA addresses the memory bottleneck of standard Transformer models. It can be used as a general model architecture to reduce memory usage and improve inference efficiency. |
| 17 | 20 | ||
| 18 | ## Usage | 21 | ## Usage |
| 19 | 22 | ||
| 20 | To enable MLA, add the following parameter configuration to your training script: | 23 | To enable MLA, add the following parameter configuration to your training script: |
| 21 | 24 | ||
| 22 | -`--multi-latent-attention`:Use Multi-Head Latent Attention | 25 | +`--multi-latent-attention`: Use Multi-Head Latent Attention |
| 23 | 26 | ||
| 24 | -`--q-lora-rank`:Rank of Query tensor's low rank representation | 27 | +`--q-lora-rank`: Rank of Query tensor's low rank representation |
| 25 | 28 | ||
| 26 | -`--kv-lora-rank`:Rank of Key and Value tensors' low rank representation | 29 | +`--kv-lora-rank`: Rank of Key and Value tensors' low rank representation |
| 27 | 30 | ||
| 28 | -`--qk-head-dim`:Dimension of the head in the QK projection. q_head_dim = qk_head_dim + qk_pos_emb_head_dim | 31 | +`--qk-head-dim`: Dimension of the head in the QK projection. q_head_dim = qk_head_dim + qk_pos_emb_head_dim |
| 29 | 32 | ||
| 30 | -`--qk-pos-emb-head-dim`:Dimension of the position embedding in the QK projection | 33 | +`--qk-pos-emb-head-dim`: Dimension of the position embedding in the QK projection |
| 31 | 34 | ||
| 32 | -`--v-head-dim`:Dimension of the head in the V projection | 35 | +`--v-head-dim`: Dimension of the head in the V projection |
| 33 | 36 | ||
| 34 | -`--rotary-scaling-factor`:Rotary scaling factor for the rotary embeddings | 37 | +`--rotary-scaling-factor`: Rotary scaling factor for the rotary embeddings |
| 38 | + | ||
| 39 | +For DSA parameters, see [DSA](deepseek-sparse-attention.md). | ||
| 35 | 40 | ||
| 36 | ## Performance | 41 | ## Performance |
| 37 | 42 | ||
| @@ -1,50 +0,0 @@ | |||
| 1 | -# Multi-Parameter Pipeline | ||
| 2 | - | ||
| 3 | -## Background and Challenges | ||
| 4 | - | ||
| 5 | -In distributed training of large deep learning models, Pipeline Parallelism (PP) is a technique that splits a model into multiple stages and executes them concurrently on different devices to improve efficiency. However, when introducing multi-parameter passing support in multimodal scenarios, PP faces specific challenges: | ||
| 6 | - | ||
| 7 | -- Communication design: Traditional PP typically involves the transmission of only a single tensor, but in the case of multi-parameter passing, the transfer of multiple variables must be handled. This not only increases communication complexity but also requires precise management of attributes such as shape and dtype for each variable. These attributes are often closely tied to the overall model architecture and are highly customized. | ||
| 8 | -- Variable passing in forward propagation: During forward computation, it is necessary not only to correctly pass multiple variables according to the defined shapes but also to ensure that the data format received by each stage meets expectations, which imposes higher requirements on data flow design. | ||
| 9 | -- Backward propagation computation extension: For backward propagation, in addition to gradient computation for the first output, corresponding operations must be performed on all other outputs to ensure the completeness and accuracy of the entire training process. | ||
| 10 | - | ||
| 11 | -## Solution | ||
| 12 | - | ||
| 13 | -To address the above challenges, the following solutions are designed to enable PP to effectively support multi-parameter passing: | ||
| 14 | - | ||
| 15 | -- Optimized communication mechanism: An efficient communication mechanism is developed to support data transmission of multiple types and formats. Transmission parameters are customized for the specific requirements of each stage. | ||
| 16 | -- Enhanced gradient computation logic: The backward propagation algorithm is improved so that the system can automatically identify and process gradient information from multiple outputs, ensuring that each output participates in the final weight update. | ||
| 17 | - | ||
| 18 | -## Application Scenario | ||
| 19 | - | ||
| 20 | -This feature is designed for large-scale neural network training tasks that involve processing extensive multimodal data — including text, images, and audio — where pipeline parallelism requires passing multiple parameters across stages. | ||
| 21 | - | ||
| 22 | -## Usage | ||
| 23 | - | ||
| 24 | -> [!NOTE] | ||
| 25 | -> | ||
| 26 | -> Users need to modify the `args.pipeline_tensor_shapes` value in the `validate_args` function within the `mindspeed/features_manager/pipeline_parallel/multi_parameter.py` module to match the tensor transmission of the actual model pipeline stages, including tensor dimensions (Shape) and data types (Dtype). | ||
| 27 | -> Incompatible with `--moe-fb-overlap` and `dualpipev`. | ||
| 28 | - | ||
| 29 | -To enable this feature, add the following parameters in the training script: | ||
| 30 | - | ||
| 31 | -- Support for PP scenarios | ||
| 32 | - | ||
| 33 | -```shell | ||
| 34 | -# PP >= 2 | ||
| 35 | ---pipeline-model-parallel-size ${PP} \ | ||
| 36 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 37 | -``` | ||
| 38 | - | ||
| 39 | -- Support for VPP scenarios | ||
| 40 | - | ||
| 41 | -```shell | ||
| 42 | -# PP >= 2, num-layers-per-virtual-pipeline-stage不为None | ||
| 43 | ---pipeline-model-parallel-size ${PP} \ | ||
| 44 | ---num-layers-per-virtual-pipeline-stage 1 \ | ||
| 45 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 46 | -``` | ||
| 47 | - | ||
| 48 | -## Effects | ||
| 49 | - | ||
| 50 | -With PP multi-parameter support, you can handle complex multimodal data more flexibly while maintaining high communication efficiency. | ||
| @@ -1,52 +0,0 @@ | |||
| 1 | -# Multi-Parameter Pipeline and Variable Sequence Lengths | ||
| 2 | - | ||
| 3 | -## Background and challenges | ||
| 4 | - | ||
| 5 | -In large-scale distributed training for deep learning, pipeline parallelism (PP) improves efficiency by partitioning a model into multiple stages and executing them concurrently on different devices. However, when processing complex multimodal data, PP faces new challenges: | ||
| 6 | - | ||
| 7 | -- For multi-parameter pipeline: Traditional PP typically involves the transfer of only a single tensor. However, in multi-parameter passing scenarios, the transfer of multiple variables must be handled. This not only increases communication complexity but also requires precise management of attributes such as the shape and dtype of each variable. | ||
| 8 | -- For variable sequence lengths: When the sequence length of input data is variable, the traditional approach is to pad all sequences to a uniform length, which leads to wasted memory and computational resources. | ||
| 9 | - | ||
| 10 | -## Solution | ||
| 11 | - | ||
| 12 | -To address these challenges, a series of optimizations have been developed: | ||
| 13 | - | ||
| 14 | -- Multi-parameter pipeline: An efficient communication mechanism has been developed to support data transmission of various types and formats, and the backpropagation algorithm has been improved so that the system can automatically identify and process gradient information from multiple outputs. | ||
| 15 | -- Variable sequence lengths: Support for dynamic shapes has been introduced, allowing sequences in each micro-batch to retain their original lengths. This is achieved by communicating the shape information of tensors in advance before sending them, synchronizing the shape of the data to be received across pipeline stages, and ensuring the accuracy of memory allocation and preprocessing. | ||
| 16 | - | ||
| 17 | -## Application Scenario | ||
| 18 | - | ||
| 19 | -- Multi-parameter pipeline: Suitable for tasks that need to process large amounts of multimodal data, such as large-scale neural network training involving text, images, and audio, where multiple parameters must be passed at each stage of the pipeline parallelism. | ||
| 20 | -- Variable sequence lengths: Ideal for tasks with significant variations in text length, such as document classification and machine translation, while also enhancing the model's generalization capability. | ||
| 21 | - | ||
| 22 | -## Usage | ||
| 23 | - | ||
| 24 | -> [!NOTE] | ||
| 25 | -> | ||
| 26 | -> Users need to modify the `args.pipeline_tensor_shapes` value in the `validate_args` function within the `mindspeed/features_manager/pipeline_parallel/multi_parameter.py` module to match the tensor transmission of the actual model's pipeline stages, including tensor dimensions (Shape) and data types (Dtype). | ||
| 27 | -> Incompatible with `--moe-fb-overlap` and `dualpipev`. | ||
| 28 | - | ||
| 29 | -To enable "multi-parameter pipeline" and "variable sequence lengths", add the following parameters to the training script: | ||
| 30 | - | ||
| 31 | -- Support for PP scenarios | ||
| 32 | - | ||
| 33 | -```shell | ||
| 34 | -# PP >= 2 | ||
| 35 | ---pipeline-model-parallel-size ${PP} \ | ||
| 36 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 37 | ---variable-seq-lengths \ | ||
| 38 | -``` | ||
| 39 | - | ||
| 40 | -- Support for VPP scenarios | ||
| 41 | - | ||
| 42 | -```shell | ||
| 43 | -# PP >= 2, num-layers-per-virtual-pipeline-stage不为None | ||
| 44 | ---pipeline-model-parallel-size ${PP} \ | ||
| 45 | ---num-layers-per-virtual-pipeline-stage 1 \ | ||
| 46 | ---use-multiparameter-pipeline-model-parallel \ | ||
| 47 | ---variable-seq-lengths \ | ||
| 48 | -``` | ||
| 49 | - | ||
| 50 | -## Effects | ||
| 51 | - | ||
| 52 | -Simultaneously supports passing multiple parameters between pipeline stages and processing variable-length input data. | ||
Mdocs/en/user-guide/performance_optimization.md+3-0File content is under review, please try again later
Mmindspeed/auto_settings/config/system_config.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/black/patch/experts.py+13-1File content is under review, please try again later
Mmindspeed/auto_settings/module/black/patch/hccl_operator.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/black/patch/language_module.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/black/patch/moe_layer.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/black/patch/router.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/communication/comm_hardware/comm_hardware_info.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/communication/comm_perf_linear_model_factory.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/communication/comm_perf_predictor.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/communication/dp_comm_perf_predictor.py+13-1File content is under review, please try again later
Mmindspeed/auto_settings/module/memory/dynamic_mem_modeling.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/memory/static_mem_modeling.py+13-1File content is under review, please try again later
Mmindspeed/auto_settings/module/memory_cost_black.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/model_performance.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_base_block.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_change_block.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_change_block_cp.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_change_block_ep.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_elemental.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_note_cal.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_re_profile.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/operator/operator_shape_cal.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/module/search/stage_1_prune_multimodal.py+14-0File content is under review, please try again later
Mmindspeed/auto_settings/profile/profiler.py+14-0File content is under review, please try again later
Mmindspeed/core/context_parallel/ulysses_context_parallel/unaligned_cp/mapping.py+13-1File content is under review, please try again later
Mmindspeed/core/data_parallel/distributed_data_parallel.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/buffer_pad/adaptor.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/comm/hookwrap.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/config.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/misc.py+13-2File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/sharded_grad_scaler.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/megatron_adaptor/optimizer/zero.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/runtime/_root_forward.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/state/fqn.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/state/mga_checkpoint.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/state/scripts/layerzero_checkpointer.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/__init__.py+14-0File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/_common_utils.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/_init_utils.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/_limiter.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/_traversal_utils.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/_wrap_utils.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/api.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/flat_param.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/layerzero/zero3/fsdp.py+13-1File content is under review, please try again later
Mmindspeed/core/distributed/param_and_grad_buffer.py+14-1File content is under review, please try again later
Rmindspeed/op_builder/fusion_attention_v2_builder.py→mindspeed/op_builder/moonep_gmm_builder.py+7-22