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/rotary_pos_embedding.py b/mindspeed/core/fusions/rotary_pos_embedding.pyindex e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..42c9f16d0777af5c65f823f41a588ad8613f34c6 100644--- a/mindspeed/core/fusions/rotary_pos_embedding.py+++ b/mindspeed/core/fusions/rotary_pos_embedding.py@@ -0,0 +1,41 @@+"""Preparation shared by rotary embedding implementations."""++import torch+from torch import Tensor+++def get_rotary_cos_sin(freqs: Tensor, dtype: torch.dtype, mscale: float = 1.0):+ """Reuse constant trigonometric tables for the lifetime of a frequency tensor.++ Decoder layers share their frequency tensor. Keeping a single entry on that+ tensor avoids retaining tables from previous forwards in a global cache.+ Trainable frequencies and inference tensors must not retain autograd state+ or supply inference-only tensors to a later training forward.+ """+ cacheable = (+ not freqs.requires_grad+ and not isinstance(mscale, Tensor)+ and not torch.is_inference_mode_enabled()+ and not freqs.is_inference()+ )+ if cacheable:+ key = (+ freqs._version,+ freqs.data_ptr(),+ freqs.shape,+ freqs.stride(),+ freqs.dtype,+ freqs.device,+ dtype,+ mscale,+ )+ cached = getattr(freqs, "_mindspeed_rotary_cos_sin", None)+ if cached is not None and cached[0] == key:+ return cached[1]++ cos = (torch.cos(freqs) * mscale).to(dtype)+ sin = (torch.sin(freqs) * mscale).to(dtype)+ result = (cos, sin)+ if cacheable:+ freqs._mindspeed_rotary_cos_sin = (key, result)+ return resultdiff --git a/mindspeed/core/fusions/tests/test_rotary_cache.py b/mindspeed/core/fusions/tests/test_rotary_cache.pynew file mode 100644index 0000000000000000000000000000000000000000..1eabcf8f187440b573b147b16ec1b253e1d524ba--- /dev/null+++ b/mindspeed/core/fusions/tests/test_rotary_cache.py@@ -0,0 +1,90 @@+"""Regression tests for sharing constant RoPE tables across decoder layers."""++import weakref++import pytest+import torch++from mindspeed.core.fusions.rotary_pos_embedding import get_rotary_cos_sin+++def assert_tables_equal(freqs, dtype, scale, tables):+ expected = ((freqs.cos() * scale).to(dtype), (freqs.sin() * scale).to(dtype))+ for actual, reference in zip(tables, expected):+ torch.testing.assert_close(actual, reference, rtol=0, atol=0)+++@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])+@pytest.mark.parametrize("scale", [1.0, 1.25])+def test_constant_tables_are_reused(dtype, scale):+ freqs = torch.linspace(-3.0, 3.0, 128).reshape(8, 1, 1, 16)+ tables = get_rotary_cos_sin(freqs, dtype, scale)+ assert get_rotary_cos_sin(freqs, dtype, scale) is tables+ assert_tables_equal(freqs, dtype, scale, tables)+++def test_mutation_dtype_and_scale_invalidate_cache():+ freqs = torch.arange(16, dtype=torch.float32)+ old = get_rotary_cos_sin(freqs, torch.float32)+ freqs.add_(0.25)+ new = get_rotary_cos_sin(freqs, torch.float32)+ assert new is not old+ assert_tables_equal(freqs, torch.float32, 1.0, new)+ for dtype, scale in [(torch.bfloat16, 1.0), (torch.bfloat16, 1.5)]:+ old, new = new, get_rotary_cos_sin(freqs, dtype, scale)+ assert new is not old+ assert_tables_equal(freqs, dtype, scale, new)+++def test_replacing_storage_invalidates_cache():+ freqs = torch.arange(16, dtype=torch.float32)+ old = get_rotary_cos_sin(freqs, torch.float32)+ freqs.data = freqs.data + 0.5+ new = get_rotary_cos_sin(freqs, torch.float32)+ assert new is not old+ assert_tables_equal(freqs, torch.float32, 1.0, new)+++def test_trainable_frequencies_support_repeated_backward():+ freqs = torch.arange(16, dtype=torch.float64, requires_grad=True)+ reference = freqs.detach().clone().requires_grad_()+ for _ in range(2):+ cos, sin = get_rotary_cos_sin(freqs, freqs.dtype, 1.25)+ (cos + sin).sum().backward()+ ((reference.cos() * 1.25) + (reference.sin() * 1.25)).sum().backward()+ torch.testing.assert_close(freqs.grad, reference.grad, rtol=0, atol=0)+ assert not hasattr(freqs, "_mindspeed_rotary_cos_sin")+++def test_tensor_scale_is_not_cached():+ freqs = torch.arange(16, dtype=torch.float32)+ scale = torch.tensor(1.25, requires_grad=True)+ for _ in range(2):+ cos, sin = get_rotary_cos_sin(freqs, freqs.dtype, scale)+ (cos + sin).sum().backward()+ assert scale.grad is not None+ assert not hasattr(freqs, "_mindspeed_rotary_cos_sin")+++def test_inference_tables_do_not_leak_into_training():+ freqs = torch.arange(16, dtype=torch.float32)+ with torch.inference_mode():+ cos, _ = get_rotary_cos_sin(freqs, freqs.dtype)+ assert cos.is_inference()+ inference_freqs = freqs.clone()+ assert not hasattr(freqs, "_mindspeed_rotary_cos_sin")+ for source in (freqs, inference_freqs):+ cos, _ = get_rotary_cos_sin(source, source.dtype)+ assert not cos.is_inference()+ x = torch.ones_like(cos, requires_grad=True)+ (x * cos).sum().backward()+ torch.testing.assert_close(x.grad, cos, rtol=0, atol=0)+++def test_cache_does_not_retain_frequency_tensors():+ freqs = torch.arange(16, dtype=torch.float32)+ ref = weakref.ref(freqs)+ tables = get_rotary_cos_sin(freqs, freqs.dtype)+ del freqs+ assert ref() is None+ assert tables[0].numel() == 16
mindspeed_llm · 3 changed files
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
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..d12ed3c6867d9341939b69233af107602b20a939 100644--- a/mindspeed_llm/core/models/common/embeddings/rotary_pos_embedding.py+++ b/mindspeed_llm/core/models/common/embeddings/rotary_pos_embedding.py@@ -12,6 +12,7 @@ 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.ops.npu_rotary_position_embedding import npu_rotary_position_embedding+from mindspeed.core.fusions.rotary_pos_embedding import get_rotary_cos_sin from mindspeed_llm.tasks.common.yarn_rope import YarnRotaryPositionEmbedding @@ -255,8 +256,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_rotary_cos_sin(freqs, t.dtype, _mscale) if args.use_fused_rotary_pos_emb: mode = 1 if rotary_interleaved else 0@@ -264,7 +264,7 @@ def apply_rotary_pos_emb_bshd( else: t = (t * cos_) + (_rotate_half(t, rotary_interleaved) * sin_) - return torch.cat((t, t_pass), dim=-1)+ return torch.cat((t, t_pass), dim=-1) if t_pass.shape[-1] else t def apply_rotary_pos_emb_thd(@@ -292,7 +292,10 @@ def apply_rotary_pos_emb_thd( # when args.reset_position_ids is False, use chunk is faster. cp_size = parallel_state.get_context_parallel_world_size() cp_rank = parallel_state.get_context_parallel_rank()- freqs = freqs.chunk(cp_size, dim=0)[cp_rank]+ # Keep the shared tensor when no partitioning is needed so all layers+ # can reuse its constant sine/cosine tables.+ if cp_size > 1:+ freqs = freqs.chunk(cp_size, dim=0)[cp_rank] return apply_rotary_pos_emb_bshd(t, freqs, rotary_interleaved, multi_latent_attention, mscale) @@ -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/utils.py b/mindspeed_llm/training/utils.pyindex c779adfcf9140eff6e1cae1ac28f45027763ff74..4e8d7b7c3324652a558993b81fd5607c3758f2a1 100644--- a/mindspeed_llm/training/utils.py+++ b/mindspeed_llm/training/utils.py@@ -587,7 +587,16 @@ def get_batch_on_this_tp_rank(data_iterator): else: _broadcast(batch['attention_mask']) if args.reset_attention_mask:- actual_seq_len = broadcast_dynamic(data['actual_seq_len'])+ if (mpu.get_tensor_model_parallel_world_size() == 1+ and args.context_parallel_size == 1+ and not args.mtp_num_layers):+ # FlashAttention takes cumulative lengths as host integers.+ # The dataloader already supplies them on the host; without+ # TP broadcast or CP padding there is no device work to do on+ # this metadata. Avoid an H2D/D2H round trip and stream sync.+ actual_seq_len = data['actual_seq_len']+ else:+ actual_seq_len = broadcast_dynamic(data['actual_seq_len']) if args.attention_mask_type == 'causal' \ and args.context_parallel_size > 1 \ and args.context_parallel_algo == 'megatron_cp_algo':@@ -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..2dc0b226af2244ec57aef037c16ac1ae613cf48b 100644--- a/pretrain_gpt.py+++ b/pretrain_gpt.py@@ -306,4 +306,11 @@ def main(): if __name__ == "__main__":- main()+ try:+ main()+ finally:+ # Shut down collectives while Python and the device runtime are still+ # alive, including normal checkpoint/exit-interval SystemExit paths.+ if torch.distributed.is_initialized():+ torch.cuda.synchronize()+ torch.distributed.destroy_process_group()