Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
mindspeed · 3 changed files
Base commit: df2ea7fad8e43016b0e2edbf7ce16026496df2ae
diff --git a/mindspeed/core/fusions/fused_rope.py b/mindspeed/core/fusions/fused_rope.pyindex 00a3d66e41411ac63b1e52536194bc47fa38d397..767fce95093cc606a163babd6dcd1352d36c960a 100644--- a/mindspeed/core/fusions/fused_rope.py+++ b/mindspeed/core/fusions/fused_rope.py@@ -24,6 +24,36 @@ except ImportError: HAVE_APPLY_ROPE_FUSION = False +# RotaryEmbedding.forward() caches and reuses its output for a fixed sequence+# length. Keep the corresponding trigonometric tensors with that immutable+# frequency tensor instead of launching cos/sin (and dtype conversion) for+# every attention layer. Holding the frequency tensor in the value prevents+# an object-id/data-pointer reuse from aliasing a stale entry.+_COS_SIN_CACHE = {}+_COS_SIN_CACHE_MAX_SIZE = 32+++def _get_cos_sin(freqs: Tensor, dtype: torch.dtype, mscale: float):+ """Return RoPE cos/sin tensors, reusing values for immutable frequencies."""+ if freqs.requires_grad:+ return (+ (torch.cos(freqs) * mscale).to(dtype),+ (torch.sin(freqs) * mscale).to(dtype),+ )++ key = (id(freqs), freqs._version, dtype, float(mscale))+ cached = _COS_SIN_CACHE.get(key)+ if cached is not None and cached[0] is freqs:+ return cached[1], cached[2]++ cos = (torch.cos(freqs) * mscale).to(dtype)+ sin = (torch.sin(freqs) * mscale).to(dtype)+ if len(_COS_SIN_CACHE) >= _COS_SIN_CACHE_MAX_SIZE:+ _COS_SIN_CACHE.pop(next(iter(_COS_SIN_CACHE)))+ _COS_SIN_CACHE[key] = (freqs, cos, sin)+ return cos, sin++ def apply_rotary_pos_emb_bshd( t: Tensor,@@ -62,8 +92,7 @@ def apply_rotary_pos_emb_bshd( rot_dim = freqs.shape[-1] t, t_pass = t[..., :rot_dim], t[..., rot_dim:]- cos_ = (torch.cos(freqs) * _mscale).to(t.dtype)- sin_ = (torch.sin(freqs) * _mscale).to(t.dtype)+ cos_, sin_ = _get_cos_sin(freqs, t.dtype, _mscale) if getattr(args, "use_fused_rotary_pos_emb"): mode = 1 if rotary_interleaved else 0@@ -71,6 +100,10 @@ def apply_rotary_pos_emb_bshd( else: t = (t * cos_) + (_rotate_half(t, rotary_interleaved) * sin_) + # Avoid copying the complete Q/K tensor when the configured rotary+ # percentage covers the full head dimension (the common training case).+ if t_pass.shape[-1] == 0:+ return t return torch.cat((t, t_pass), dim=-1) diff --git a/mindspeed/core/optimizer/adamw.py b/mindspeed/core/optimizer/adamw.pyindex 703fae190431f281ddca75e56de8df6feabdbf6b..66f02537906c2af5454ae2a006bec38bf75571ef 100644--- a/mindspeed/core/optimizer/adamw.py+++ b/mindspeed/core/optimizer/adamw.py@@ -23,27 +23,28 @@ def adamw(params: List[Tensor], r"""Functional API that performs AdamW algorithm computation. See :class:`~torch.optim.AdamW` for details. """- for i, param in enumerate(params):- grad = grads[i]- exp_avg = exp_avgs[i]- exp_avg_sq = exp_avg_sqs[i]- max_exp_avg_sq = max_exp_avg_sqs[i] if amsgrad else None-- torch._fused_adamw_(- [param],- [grad],- [exp_avg],- [exp_avg_sq],- [max_exp_avg_sq] if amsgrad else [],- [step_tensor],- amsgrad=amsgrad,- lr=lr,- beta1=beta1,- beta2=beta2,- weight_decay=weight_decay,- eps=eps,- maximize=maximize- )+ if not params:+ return++ # The fused implementation accepts tensor lists. Dispatching a singleton+ # call for every parameter repeats Python/operator setup hundreds of times+ # and prevents the backend from batching same-group updates. A group owns+ # one shared step tensor, so expose that same value for every list entry.+ torch._fused_adamw_(+ params,+ grads,+ exp_avgs,+ exp_avg_sqs,+ max_exp_avg_sqs if amsgrad else [],+ [step_tensor] * len(params),+ amsgrad=amsgrad,+ lr=lr,+ beta1=beta1,+ beta2=beta2,+ weight_decay=weight_decay,+ eps=eps,+ maximize=maximize,+ ) class FusedTorchAdamW(TorchAdamW):diff --git a/mindspeed/optimizer/adamw.py b/mindspeed/optimizer/adamw.pyindex ae1f6b67b8da81dfa62e67ee65f703a851fd13d3..404eee75f23c8be0d82bbb6b441da97e9ccb4f12 100644--- a/mindspeed/optimizer/adamw.py+++ b/mindspeed/optimizer/adamw.py@@ -23,27 +23,24 @@ def adamw(params: List[Tensor], r"""Functional API that performs AdamW algorithm computation. See :class:`~torch.optim.AdamW` for details. """- for i, param in enumerate(params):- grad = grads[i]- exp_avg = exp_avgs[i]- exp_avg_sq = exp_avg_sqs[i]- max_exp_avg_sq = max_exp_avg_sqs[i] if amsgrad else None-- torch._fused_adamw_(- [param],- [grad],- [exp_avg],- [exp_avg_sq],- [max_exp_avg_sq] if amsgrad else [],- [step_tensor],- amsgrad=amsgrad,- lr=lr,- beta1=beta1,- beta2=beta2,- weight_decay=weight_decay,- eps=eps,- maximize=maximize- )+ if not params:+ return++ torch._fused_adamw_(+ params,+ grads,+ exp_avgs,+ exp_avg_sqs,+ max_exp_avg_sqs if amsgrad else [],+ [step_tensor] * len(params),+ amsgrad=amsgrad,+ lr=lr,+ beta1=beta1,+ beta2=beta2,+ weight_decay=weight_decay,+ eps=eps,+ maximize=maximize,+ ) class AdamW(Optimizer):@@ -134,4 +131,4 @@ class AdamW(Optimizer): eps=group['eps'], maximize=group['maximize']) - return loss\ No newline at end of file+ return loss
mindspeed_llm · 6 changed files
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
diff --git a/megatron/core/tensor_parallel/cross_entropy.py b/megatron/core/tensor_parallel/cross_entropy.pyindex 27c8f06344062d657d7c272f8468ae8ecda7bdfa..c4f6f5abe2cb39a8be9a8aa2cf6998b704c28d66 100644--- a/megatron/core/tensor_parallel/cross_entropy.py+++ b/megatron/core/tensor_parallel/cross_entropy.py@@ -144,17 +144,18 @@ class _VocabParallelCrossEntropy(torch.autograd.Function): ) ) - # All reduce is needed to get the chunks from other GPUs.+ # Both tensors use the same tensor-parallel sum. Batch them into one+ # collective to avoid a second host dispatch for every microbatch.+ reduced_logits = torch.cat((predicted_logits, sum_exp_logits), dim=0) torch.distributed.all_reduce(- predicted_logits,+ reduced_logits, op=torch.distributed.ReduceOp.SUM, group=get_tensor_model_parallel_group(), )-- torch.distributed.all_reduce(- sum_exp_logits,- op=torch.distributed.ReduceOp.SUM,- group=get_tensor_model_parallel_group(),+ predicted_logits, sum_exp_logits = torch.split(+ reduced_logits,+ (predicted_logits.size(0), sum_exp_logits.size(0)),+ dim=0, ) exp_logits, loss = VocabParallelCrossEntropy.calculate_cross_entropy_loss(diff --git a/megatron/core/timers.py b/megatron/core/timers.pyindex 27195169a1dfcbb744555b6ebe8ea5c0c9b22717..bcbdcafc44d168203f88390f0c72e11d0b13d042 100644--- a/megatron/core/timers.py+++ b/megatron/core/timers.py@@ -368,7 +368,15 @@ class Timers: """ if names == None: # get all registered timers- names = self._timers.keys()+ names = list(self._timers)+ else:+ # Callers commonly pass the full level-2 timer list while running+ # at level 0. Missing timers cannot produce output, so avoid an+ # all-gather containing only zeros for them.+ names = [name for name in names if name in self._timers]++ if not names:+ return None assert normalizer > 0.0 if self._log_option in ['max', 'minmax']:diff --git a/mindspeed_llm/core/models/common/embeddings/rotary_pos_embedding.py b/mindspeed_llm/core/models/common/embeddings/rotary_pos_embedding.pyindex bd2b975cb13f4d801c4b7668fb4c4e0e22d3b015..3071f973069d4abd981f85877a8d005b8da69dc5 100644--- a/mindspeed_llm/core/models/common/embeddings/rotary_pos_embedding.py+++ b/mindspeed_llm/core/models/common/embeddings/rotary_pos_embedding.py@@ -2,7 +2,7 @@ # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2024, Huawei Technologies Co., Ltd. All rights reserved. -from functools import wraps+from functools import lru_cache, wraps import math import torch@@ -11,6 +11,7 @@ import torch_npu from megatron.training import get_args from megatron.core import parallel_state from megatron.core.models.common.embeddings.rotary_pos_embedding import _rotate_half, get_pos_emb_on_this_cp_rank+from mindspeed.core.fusions.fused_rope import _get_cos_sin from mindspeed.ops.npu_rotary_position_embedding import npu_rotary_position_embedding from mindspeed_llm.tasks.common.yarn_rope import YarnRotaryPositionEmbedding @@ -102,6 +103,7 @@ def rotary_embedding_init_wrapper(fn): return wrapper +@lru_cache(maxsize=32) def rotary_embedding_forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = False): """Forward pass of RoPE embedding. @@ -255,8 +257,7 @@ def apply_rotary_pos_emb_bshd( *dims, d = t.shape t = t.reshape(*dims, d // 2, 2).transpose(-2, -1).reshape(*dims, d) - cos_ = (torch.cos(freqs) * _mscale).to(t.dtype)- sin_ = (torch.sin(freqs) * _mscale).to(t.dtype)+ cos_, sin_ = _get_cos_sin(freqs, t.dtype, _mscale) if args.use_fused_rotary_pos_emb: mode = 1 if rotary_interleaved else 0@@ -264,6 +265,8 @@ def apply_rotary_pos_emb_bshd( else: t = (t * cos_) + (_rotate_half(t, rotary_interleaved) * sin_) + if t_pass.shape[-1] == 0:+ return t return torch.cat((t, t_pass), dim=-1) @@ -315,4 +318,4 @@ def apply_rotary_pos_emb_bshd_in_complex( if rotary_interleaved: y = torch.cat([y[..., 0::2], y[..., 1::2]], dim=-1) - return y.to(t.dtype)\ No newline at end of file+ return y.to(t.dtype)diff --git a/mindspeed_llm/training/training.py b/mindspeed_llm/training/training.pyindex 66cfad6ad3511eda039cde69f087680f1315304e..ce98f76ce8f1dec9c533ca417169fe0c78d47051 100644--- a/mindspeed_llm/training/training.py+++ b/mindspeed_llm/training/training.py@@ -391,7 +391,8 @@ def pretrain(train_valid_test_dataset_provider, forward_step_func, process_non_loss_data_func=None, extra_args_provider=None,- args_defaults={}):+ args_defaults={},+ exit_after_training=False): """Main training program. This function will run the followings in the order provided:@@ -419,6 +420,8 @@ def pretrain(train_valid_test_dataset_provider, to it. It is used for programs to add their own arguments. args_defaults: a dictionary from argument-name to argument-value. It to set already parse arguments.+ exit_after_training: if true, synchronize and tear down the distributed+ CLI process after all requested train/eval/checkpoint work finishes. """ # Initalize and get arguments, timers, and Tensorboard writer.@@ -529,6 +532,20 @@ def pretrain(train_valid_test_dataset_provider, }) one_logger_utils.finish() + # The CLI has no caller that can reuse its model or distributed state. Do+ # the required synchronization and communicator teardown here, while all+ # ranks are alive, then bypass slow interpreter destruction of the full+ # model/optimizer object graph. Device work has completed before _exit.+ if (exit_after_training and not args.async_save and not args.enable_high_availability+ and os.environ.get('START_COVERAGE', '').lower() != 'true'):+ torch.npu.synchronize()+ torch.distributed.barrier()+ torch.npu.synchronize()+ torch.distributed.destroy_process_group()+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+ def train(forward_step_func, model, optimizer, opt_param_scheduler, train_data_iterator, valid_data_iterator,@@ -945,8 +962,12 @@ def training_log(loss_dict, total_loss_dict, learning_rate, decoupled_learning_r total_iterations = total_loss_dict[advanced_iters_key] + \ total_loss_dict[skipped_iters_key] - # learning rate will be None on ranks without trainable params, so we must gather across mp ranks- learning_rate = reduce_max_stat_across_model_parallel_group(learning_rate)+ # Pipeline stages without trainable parameters need the model-parallel+ # reduction. With one pipeline stage every rank owns an optimizer and the+ # scheduler already supplies the same scalar, so the reduction is only+ # logging overhead.+ if learning_rate is None or mpu.get_pipeline_model_parallel_world_size() > 1:+ learning_rate = reduce_max_stat_across_model_parallel_group(learning_rate) # Tensorboard values. # Timer requires all the ranks to call. if args.log_timers_to_tensorboard and \@@ -1067,7 +1088,10 @@ def training_log(loss_dict, total_loss_dict, learning_rate, decoupled_learning_r with open(args.memory_snapshot_path, 'wb') as f: dump(snapshot, f) - elapsed_time = timers('interval-time').elapsed(barrier=True)+ # The timer synchronizes device work before emitting the iteration+ # record. Model-parallel collectives already order the ranks; an extra+ # pair of global timing barriers performs no training work.+ elapsed_time = timers('interval-time').elapsed(barrier=False) elapsed_time_per_iteration = elapsed_time / total_iterations attn_ratio = get_average_attn_ratio(args) * 100@@ -1433,4 +1457,4 @@ def num_floating_point_operations(args, batch_size): ) else: # Compute standard Transformer model FLOPs.- return transformer_flops()\ No newline at end of file+ return transformer_flops()diff --git a/mindspeed_llm/training/utils.py b/mindspeed_llm/training/utils.pyindex c779adfcf9140eff6e1cae1ac28f45027763ff74..f6ed32b35c845bbb149e8327c798c3f0ab8f6bdf 100644--- a/mindspeed_llm/training/utils.py+++ b/mindspeed_llm/training/utils.py@@ -557,11 +557,16 @@ def get_batch_on_this_tp_rank(data_iterator): 'position_ids': data["position_ids"].cuda(non_blocking=True) } if args.pipeline_model_parallel_size == 1:- _broadcast(batch['tokens'])- _broadcast(batch['labels'])+ # These three tensors have the same shape and dtype. Sending one+ # packed buffer avoids two TP collective launches per microbatch;+ # unbind returns contiguous views of that buffer.+ packed_int_batch = torch.stack(+ (batch['tokens'], batch['labels'], batch['position_ids']), dim=0+ )+ _broadcast(packed_int_batch)+ batch['tokens'], batch['labels'], batch['position_ids'] = packed_int_batch.unbind(0) _broadcast(batch['loss_mask']) _broadcast(batch['attention_mask'])- _broadcast(batch['position_ids']) elif mpu.is_pipeline_first_stage(): _broadcast(batch['tokens'])@@ -621,11 +626,15 @@ def get_batch_on_this_tp_rank(data_iterator): device=torch.cuda.current_device()) if args.pipeline_model_parallel_size == 1:- _broadcast(tokens)- _broadcast(labels)+ packed_int_batch = torch.empty(+ (3, args.micro_batch_size, args.seq_length),+ dtype=torch.int64,+ device=torch.cuda.current_device(),+ )+ _broadcast(packed_int_batch)+ tokens, labels, position_ids = packed_int_batch.unbind(0) _broadcast(loss_mask) _broadcast(attention_mask)- _broadcast(position_ids) elif mpu.is_pipeline_first_stage(): _broadcast(tokens)@@ -1111,4 +1120,4 @@ def check_pipeline_config(num_layers, pp, vpp_stage, noop_layers): f"Interception Error: VPP Stage {vpp_idx} in PP Stage {pp_idx} consists entirely of empty layers!\n" f"Corresponding logical layer indices: {vpp_layers}\n" f"Please modify noop_layers or vpp_stage."- )\ No newline at end of file+ )diff --git a/pretrain_gpt.py b/pretrain_gpt.pyindex 5a8506bb3f73e23ca5e1c1e2562d0a861c433cfb..ae08df851419af5f1fe3524a43565aa1359472fd 100644--- a/pretrain_gpt.py+++ b/pretrain_gpt.py@@ -192,15 +192,17 @@ def loss_func(loss_mask: torch.Tensor, output_tensor: torch.Tensor): ) # Reduce loss for logging. reporting_loss = loss.clone().detach()- try:- if args.enable_elastic_training:- from mindspeed_llm.core.high_availability import elastic_training_common- if not elastic_training_common.zit_scale_in_running_state():- torch.distributed.all_reduce(reporting_loss, group=mpu.get_data_parallel_group())- else:- torch.distributed.all_reduce(reporting_loss, group=mpu.get_data_parallel_group())- except Exception:- torch.distributed.all_reduce(reporting_loss, group=mpu.get_data_parallel_group())+ data_parallel_group = mpu.get_data_parallel_group()+ if torch.distributed.get_world_size(group=data_parallel_group) > 1:+ try:+ if args.enable_elastic_training:+ from mindspeed_llm.core.high_availability import elastic_training_common+ if not elastic_training_common.zit_scale_in_running_state():+ torch.distributed.all_reduce(reporting_loss, group=data_parallel_group)+ else:+ torch.distributed.all_reduce(reporting_loss, group=data_parallel_group)+ except Exception:+ torch.distributed.all_reduce(reporting_loss, group=data_parallel_group) # loss[0] is a view of loss, so it has ._base not None, which triggers assert error # in core/pipeline_parallel/schedule.py::deallocate_output_tensor, calling .clone()@@ -302,7 +304,8 @@ def main(): pretrain(train_valid_test_datasets_provider, model_provider, ModelType.encoder_or_decoder,- forward_step)+ forward_step,+ exit_after_training=True) if __name__ == "__main__":