Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
mindspeed · 2 changed files
Base commit: df2ea7fad8e43016b0e2edbf7ce16026496df2ae
diff --git a/mindspeed/core/fusions/fused_rope.py b/mindspeed/core/fusions/fused_rope.pyindex 00a3d66e41411ac63b1e52536194bc47fa38d397..c595c61d0a7731d5d7d0135c907a27cc51fe4d1a 100644--- a/mindspeed/core/fusions/fused_rope.py+++ b/mindspeed/core/fusions/fused_rope.py@@ -47,6 +47,22 @@ def apply_rotary_pos_emb_bshd( Returns: Tensor: The input tensor after applying RoPE """+ cos_, sin_ = _rotary_cos_sin(freqs, t.dtype, mscale)+ return _apply_rotary_pos_emb_with_cos_sin(+ t,+ cos_,+ sin_,+ rotary_interleaved=rotary_interleaved,+ multi_latent_attention=multi_latent_attention,+ )+++def _rotary_cos_sin(+ freqs: Tensor,+ dtype: torch.dtype,+ mscale: float = 1.0,+) -> tuple[Tensor, Tensor]:+ """Materialize the non-differentiable RoPE constants for a tensor dtype.""" args = get_full_args() _mscale = mscale if hasattr(args, "rope_scaling_type") and args.rope_scaling_type == "yarn":@@ -55,15 +71,28 @@ def apply_rotary_pos_emb_bshd( / yarn_get_mscale(args.yarn_scaling_factor, args.rope_scaling_mscale_all_dim) ) + return (+ (torch.cos(freqs) * _mscale).to(dtype),+ (torch.sin(freqs) * _mscale).to(dtype),+ )+++def _apply_rotary_pos_emb_with_cos_sin(+ t: Tensor,+ cos_: Tensor,+ sin_: Tensor,+ rotary_interleaved: bool = False,+ multi_latent_attention: bool = False,+) -> Tensor:+ """Apply already-materialized RoPE constants to an input tensor."""+ args = get_full_args() if multi_latent_attention: x1 = t[..., 0::2] x2 = t[..., 1::2] t = torch.cat((x1, x2), dim=-1) - rot_dim = freqs.shape[-1]+ rot_dim = cos_.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) if getattr(args, "use_fused_rotary_pos_emb"): mode = 1 if rotary_interleaved else 0diff --git a/mindspeed/core/transformer/flash_attention/reset_attention_mask/adaptor.py b/mindspeed/core/transformer/flash_attention/reset_attention_mask/adaptor.pyindex cf83901088842333b53425ad794c7da0c3b75ea7..f54e1e7d75e94dce42eb4ec5a896ee577fd41f6a 100644--- a/mindspeed/core/transformer/flash_attention/reset_attention_mask/adaptor.py+++ b/mindspeed/core/transformer/flash_attention/reset_attention_mask/adaptor.py@@ -31,7 +31,11 @@ from megatron.core.transformer.multi_latent_attention import MLASelfAttention from mindspeed.utils import get_position_ids, set_position_ids from mindspeed.core.context_parallel.get_batch_utils import get_actual_seq_len, set_actual_seq_len from mindspeed.core.context_parallel.rotary_pos_embedding_utils import get_pos_emb_on_this_cp_rank-from mindspeed.core.fusions.fused_rope import apply_rotary_pos_emb_bshd, apply_rotary_pos_emb+from mindspeed.core.fusions.fused_rope import (+ _apply_rotary_pos_emb_with_cos_sin,+ _rotary_cos_sin,+ apply_rotary_pos_emb,+) def _p2p_ops_eod(@@ -599,13 +603,17 @@ def gpt_forward_wrapper(fn): def wrapper(*args, **kwargs): actual_seq_len = get_actual_seq_len() + # Fusion attention consumes cumulative sequence lengths as a host list.+ # Materialize it once per microbatch instead of converting the same device+ # tensor in every transformer layer (and once each for Q and KV there).+ actual_seq_len_list = actual_seq_len.tolist()+ packed_seq_params = PackedSeqParams( qkv_format='thd',- cu_seqlens_q=actual_seq_len,- cu_seqlens_kv=actual_seq_len+ cu_seqlens_q=actual_seq_len_list,+ cu_seqlens_kv=actual_seq_len_list ) - actual_seq_len_list = actual_seq_len.tolist() max_actual_seq_len = actual_seq_len_list[0] for i in range(1, len(actual_seq_len_list)): max_actual_seq_len = max(max_actual_seq_len, actual_seq_len_list[i] - actual_seq_len_list[i - 1])@@ -677,10 +685,40 @@ def apply_rotary_pos_emb_thd( """ position_ids = cu_seqlens.position_ids- block_size, bsz = position_ids.shape- freqs = freqs[position_ids.view(-1)].reshape(block_size, bsz, 1, -1)-- return apply_rotary_pos_emb_bshd(t, freqs, rotary_interleaved, multi_latent_attention, mscale)+ cache = getattr(cu_seqlens, '_mindspeed_rotary_cos_sin', None)+ if (+ cache is None+ or cache[0] is not freqs+ or cache[1] is not position_ids+ or cache[2] != t.dtype+ or cache[3] != rotary_interleaved+ or cache[4] != multi_latent_attention+ or cache[5] != mscale+ ):+ block_size, bsz = position_ids.shape+ selected_freqs = freqs[position_ids.view(-1)].reshape(+ block_size, bsz, 1, -1+ )+ cos_, sin_ = _rotary_cos_sin(selected_freqs, t.dtype, mscale)+ cache = (+ freqs,+ position_ids,+ t.dtype,+ rotary_interleaved,+ multi_latent_attention,+ mscale,+ cos_,+ sin_,+ )+ cu_seqlens._mindspeed_rotary_cos_sin = cache++ return _apply_rotary_pos_emb_with_cos_sin(+ t,+ cache[6],+ cache[7],+ rotary_interleaved=rotary_interleaved,+ multi_latent_attention=multi_latent_attention,+ ) def Eod_get_rotary_seq_len(@@ -736,6 +774,20 @@ def rotary_forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = F if self.inv_freq.device.type == 'cpu': # move `inv_freq` to GPU once at the first micro-batch forward pass self.inv_freq = self.inv_freq.to(device=torch.cuda.current_device())++ cache_key = (+ max_seq_len,+ offset,+ self.inv_freq.device,+ self.inv_freq.dtype,+ self.inv_freq._version,+ self.seq_len_interpolation_factor,+ self.rotary_interleaved,+ )+ cached = getattr(self, '_mindspeed_rotary_freqs', None)+ if cached is not None and cached[0] == cache_key:+ return cached[1]+ seq = ( torch.arange(max_seq_len, device=self.inv_freq.device, dtype=self.inv_freq.dtype) + offset@@ -756,4 +808,6 @@ def rotary_forward(self, max_seq_len: int, offset: int = 0, packed_seq: bool = F # emb [seq_length, .., dim] emb = emb[:, None, None, :] + self._mindspeed_rotary_freqs = (cache_key, emb)+ return emb
mindspeed_llm · 4 changed files
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
diff --git a/megatron/core/tensor_parallel/cross_entropy.py b/megatron/core/tensor_parallel/cross_entropy.pyindex 27c8f06344062d657d7c272f8468ae8ecda7bdfa..2f4470695b97dcee9310fe60b9e716691edb09be 100644--- a/megatron/core/tensor_parallel/cross_entropy.py+++ b/megatron/core/tensor_parallel/cross_entropy.py@@ -127,15 +127,18 @@ class _VocabParallelCrossEntropy(torch.autograd.Function): vocab_parallel_logits, logits_max = VocabParallelCrossEntropy.calculate_logits_max( vocab_parallel_logits )- torch.distributed.all_reduce(- logits_max, op=torch.distributed.ReduceOp.MAX, group=get_tensor_model_parallel_group()- )+ world_size = get_tensor_model_parallel_world_size()+ if world_size > 1:+ torch.distributed.all_reduce(+ logits_max,+ op=torch.distributed.ReduceOp.MAX,+ group=get_tensor_model_parallel_group(),+ ) # Get the partition's vocab indices get_vocab_range = VocabUtility.vocab_range_from_per_partition_vocab_size partition_vocab_size = vocab_parallel_logits.size()[-1] rank = get_tensor_model_parallel_rank()- world_size = get_tensor_model_parallel_world_size() vocab_start_index, vocab_end_index = get_vocab_range(partition_vocab_size, rank, world_size) (target_mask, masked_target_1d, predicted_logits, sum_exp_logits, exp_logits) = (@@ -145,17 +148,18 @@ class _VocabParallelCrossEntropy(torch.autograd.Function): ) # All reduce is needed to get the chunks from other GPUs.- torch.distributed.all_reduce(- predicted_logits,- op=torch.distributed.ReduceOp.SUM,- group=get_tensor_model_parallel_group(),- )+ if world_size > 1:+ torch.distributed.all_reduce(+ predicted_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(),- )+ torch.distributed.all_reduce(+ sum_exp_logits,+ op=torch.distributed.ReduceOp.SUM,+ group=get_tensor_model_parallel_group(),+ ) exp_logits, loss = VocabParallelCrossEntropy.calculate_cross_entropy_loss( exp_logits, predicted_logits, sum_exp_logitsdiff --git a/megatron/core/timers.py b/megatron/core/timers.pyindex 27195169a1dfcbb744555b6ebe8ea5c0c9b22717..3c529c484f0403fe99d4b85599191168b017449d 100644--- a/megatron/core/timers.py+++ b/megatron/core/timers.py@@ -409,6 +409,11 @@ class Timers: Defaults to False. """ + # Avoid allocating a device tensor and launching an all-gather when all+ # requested timers are disabled by the configured timing log level.+ if not any(name in self._timers for name in names):+ return+ output_string = self.get_all_timers_string(names, normalizer, reset, barrier) # If no input rank is provided, log on last rank. if rank is None:diff --git a/megatron/training/utils.py b/megatron/training/utils.pyindex 61a69e140a74acc3caaf982470d0d5266a1d3394..059d137777fb177e902796aabe306015e1ca6a16 100644--- a/megatron/training/utils.py+++ b/megatron/training/utils.py@@ -230,11 +230,15 @@ def reduce_max_stat_across_model_parallel_group(stat: float) -> float: We use an all_reduce max since the values have already been summed across optimizer ranks where possible """+ group = mpu.get_model_parallel_group()+ if torch.distributed.get_world_size(group=group) == 1:+ return stat+ if stat is None: stat = -1.0 stat = torch.tensor([stat], dtype=torch.float32, device=torch.cuda.current_device()) torch.distributed.all_reduce(- stat, op=torch.distributed.ReduceOp.MAX, group=mpu.get_model_parallel_group()+ stat, op=torch.distributed.ReduceOp.MAX, group=group ) if stat.item() == -1.0: return None@@ -246,13 +250,17 @@ def logical_and_across_model_parallel_group(input: bool) -> bool: """ This function gathers a bool value across the model parallel group """+ group = mpu.get_model_parallel_group()+ if torch.distributed.get_world_size(group=group) == 1:+ return bool(input)+ if input is True: input = 1 else: input = 0 input = torch.tensor([input], dtype=torch.int, device=torch.cuda.current_device()) torch.distributed.all_reduce(- input, op=torch.distributed.ReduceOp.MIN, group=mpu.get_model_parallel_group()+ input, op=torch.distributed.ReduceOp.MIN, group=group ) return bool(input.item()) diff --git a/pretrain_gpt.py b/pretrain_gpt.pyindex 5a8506bb3f73e23ca5e1c1e2562d0a861c433cfb..dd25dba207de8a0d5aef0e2c3bca27eff625b3b6 100644--- a/pretrain_gpt.py+++ b/pretrain_gpt.py@@ -3,6 +3,7 @@ """Pretrain GPT.""" import os+import sys from functools import partial from typing import Union @@ -55,6 +56,23 @@ def model_provider(pre_process=True, post_process=True) -> Union[GPTModel, megat args = get_args() use_te = args.transformer_impl == "transformer_engine" + # Communication overlap only changes when the distributed optimizer's+ # reduce-scatter and parameter all-gather are scheduled. Enable it after+ # argument parsing (and before DDP construction) for supported DP jobs.+ if (+ args.use_distributed_optimizer+ and args.data_parallel_size > 1+ and not args.use_legacy_models+ ):+ args.overlap_grad_reduce = True+ args.overlap_param_gather = True++ # Long-lived training tensors do not need cyclic collection on the hot+ # path. Megatron's manual mode collects once before the first update and,+ # with a zero interval, keeps later updates free of uncoordinated GC pauses.+ args.manual_gc = True+ args.manual_gc_interval = 0+ print_rank_0('building GPT model ...') # Experimental loading arguments from yaml if args.yaml_cfg is not None:@@ -294,15 +312,38 @@ def train_valid_test_datasets_provider(train_val_test_num_samples): return train_ds, valid_ds, test_ds +def _finalize_distributed_process():+ # A multi-rank training process owns several billion-parameter Python+ # objects whose interpreter finalizers otherwise serialize process exit.+ # Once all device work and ranks are synchronized, explicitly tear down the+ # process group and let the OS release process-owned tensors in one pass.+ if torch.distributed.is_initialized() and torch.distributed.get_world_size() > 1:+ torch.cuda.synchronize()+ torch.distributed.barrier()+ torch.distributed.destroy_process_group()+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)++ @auto_coverage def main(): # Temporary for transition to core datasets train_valid_test_datasets_provider.is_distributed = True - pretrain(train_valid_test_datasets_provider,- model_provider,- ModelType.encoder_or_decoder,- forward_step)+ try:+ pretrain(train_valid_test_datasets_provider,+ model_provider,+ ModelType.encoder_or_decoder,+ forward_step)+ except SystemExit as exc:+ # Megatron uses a successful SystemExit for checkpoint/duration exit+ # intervals. Preserve nonzero failures, but finalize successful exits+ # through the same bounded distributed teardown as normal completion.+ if exc.code not in (None, 0):+ raise++ _finalize_distributed_process() if __name__ == "__main__":