Buckets:
xuan-luo/kvpath-optimization / KDA-optimization /env /third_party /Megatron-LM /tests /unit_tests /test_utils.py
| # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. | |
| import os | |
| import time | |
| import urllib.request as req | |
| from types import SimpleNamespace | |
| from unittest.mock import patch | |
| import mock | |
| import numpy as np | |
| import pytest | |
| import torch | |
| import megatron.core.utils as util | |
| import megatron.training.utils as training_util | |
| from megatron.core import config | |
| from megatron.core._rank_utils import safe_get_rank, safe_get_world_size | |
| from megatron.core.distributed import DistributedDataParallel, DistributedDataParallelConfig | |
| from megatron.core.models.gpt.gpt_layer_specs import ( | |
| get_gpt_layer_with_transformer_engine_submodules, | |
| ) | |
| from megatron.core.optimizer import OptimizerConfig, get_megatron_optimizer | |
| from megatron.core.transformer import TransformerConfig | |
| from megatron.core.transformer.moe.moe_layer import MoELayer, MoESubmodules | |
| from megatron.core.transformer.spec_utils import get_submodules | |
| from megatron.training.utils.common_utils import get_local_rank_preinit | |
| from tests.unit_tests.test_utilities import Utils | |
| success_string = "hello,world" | |
| class A: | |
| def __init__(self): | |
| pass | |
| def some_method(self): | |
| return success_string | |
| def some_static_method(cls): | |
| return success_string | |
| def test_divide_properly(): | |
| assert util.divide(4, 2) == 2 | |
| def test_divide_improperly(): | |
| with pytest.raises(AssertionError): | |
| util.divide(4, 5) | |
| def test_is_flashinfer_min_version(check_equality): | |
| from packaging.version import Version as PkgVersion | |
| with patch.object(util, "get_flashinfer_version", return_value=PkgVersion("0.6.5")): | |
| # check_equality=False exercised the path that used to reference an | |
| # undefined name and raise NameError instead of returning a bool. | |
| assert util.is_flashinfer_min_version("0.6.4", check_equality=check_equality) is True | |
| assert util.is_flashinfer_min_version("0.7.0", check_equality=check_equality) is False | |
| assert ( | |
| util.is_flashinfer_min_version("0.6.5", check_equality=check_equality) is check_equality | |
| ) | |
| with patch.object(util, "get_flashinfer_version", return_value=None): | |
| assert util.is_flashinfer_min_version("0.6.4", check_equality=check_equality) is False | |
| def test_experimental_cls_init(): | |
| with patch.object(config, 'ENABLE_EXPERIMENTAL', True): | |
| # Check that initialization works | |
| a = A() | |
| assert a.__class__.__qualname__ == "A" | |
| assert a.some_method() == success_string | |
| assert a.is_experimental is True | |
| def test_experimental_cls_static(): | |
| with patch.object(config, 'ENABLE_EXPERIMENTAL', True): | |
| # Check that static methods work | |
| assert A.__class__.__qualname__ == "A" | |
| assert A.some_static_method() == success_string | |
| assert A.is_experimental is True | |
| def test_experimental_cls_exception_init(): | |
| with ( | |
| patch.object(config, 'ENABLE_EXPERIMENTAL', False), | |
| pytest.raises(util.ExperimentalNotEnabledError), | |
| ): | |
| a = A() | |
| assert a.some_method() == success_string | |
| assert a.is_experimental is False | |
| def test_experimental_cls_exception_static(): | |
| with ( | |
| patch.object(config, 'ENABLE_EXPERIMENTAL', False), | |
| pytest.raises(util.ExperimentalNotEnabledError), | |
| ): | |
| assert A.some_static_method() == success_string | |
| assert A.is_experimental is False | |
| def test_global_memory_buffer(): | |
| global_memory_buffer = util.GlobalMemoryBuffer() | |
| obtained_tensor = global_memory_buffer.get_tensor((3, 2), torch.float32, "test_tensor") | |
| expected_tensor = torch.empty((3, 2), dtype=torch.float32, device=torch.cuda.current_device()) | |
| assert obtained_tensor.shape == expected_tensor.shape | |
| def test_global_memory_buffer_stable_after_presizing(): | |
| """Regression test for CUDA-graph corruption via GlobalMemoryBuffer growth. | |
| ``get_tensor`` is grow-only: it only reallocates the backing buffer when the | |
| cached one is missing or too small. Megatron's dynamic inference engine relies | |
| on this to keep a CUDA-graph-captured all-gather buffer's address stable -- it | |
| pre-sizes the buffer to the worst case before capturing graphs. If a *larger* | |
| request later reallocated the buffer, the freed address (still written by a | |
| captured graph on replay) would be recycled and silently corrupted. | |
| This asserts the invariant the fix depends on: once sized to the max, any | |
| smaller request reuses the SAME storage (stable device address); a larger | |
| request is the only thing that reallocates. | |
| """ | |
| gmb = util.GlobalMemoryBuffer() | |
| device = torch.cuda.current_device() | |
| # Pre-size to the worst case (mirrors create_cuda_graphs priming). | |
| max_tensor = gmb.get_tensor((128,), torch.float32, "mpu") | |
| presized_ptr = max_tensor.untyped_storage().data_ptr() | |
| # Every smaller-or-equal request must reuse the same backing storage, i.e. the | |
| # captured address never moves and is never freed. | |
| for shape in [(128,), (64,), (1,), (100,)]: | |
| t = gmb.get_tensor(shape, torch.float32, "mpu") | |
| assert t.untyped_storage().data_ptr() == presized_ptr, ( | |
| f"get_tensor({shape}) reallocated the 'mpu' buffer after pre-sizing; " | |
| "a captured CUDA graph would write to the freed address." | |
| ) | |
| # Sanity: a request larger than the pre-sized buffer is the only case that | |
| # reallocates. (This is exactly the condition the engine avoids by pre-sizing | |
| # to context.max_tokens * hidden_size before graph capture.) | |
| grown = gmb.get_tensor((256,), torch.float32, "mpu") | |
| assert grown.untyped_storage().data_ptr() != presized_ptr | |
| def test_make_viewless_tensor(): | |
| inp = torch.rand((3, 4)) | |
| assert torch.equal(inp, util.make_viewless_tensor(inp, True, True)) | |
| assert torch.equal(inp, util.make_viewless_tensor(inp, True, False)) | |
| def test_safely_set_viewless_tensor_data(): | |
| tensor = torch.zeros((3, 4)) | |
| new_data_tensor = torch.tensor(np.random.rand(3, 4)) | |
| util.safely_set_viewless_tensor_data(tensor, new_data_tensor) | |
| assert torch.equal(tensor, new_data_tensor) | |
| def test_assert_viewless_tensor(): | |
| tensor = torch.rand((3, 4)) | |
| assert torch.equal(util.assert_viewless_tensor(tensor), tensor) | |
| input_tensor_list = [tensor, tensor, tensor] | |
| output_tensor_list = util.assert_viewless_tensor(input_tensor_list) | |
| for inp, out in zip(input_tensor_list, output_tensor_list): | |
| assert torch.equal(inp, out) | |
| # Initialize torch.distributed; do not call init_process_group here, call | |
| # Utils.initialize_distributed() instead. | |
| def _init_distributed(world, rank): | |
| Utils.initialize_distributed() | |
| assert torch.distributed.is_initialized() == True | |
| assert torch.distributed.get_rank() == rank | |
| assert torch.cuda.device_count() == world | |
| torch.distributed.barrier() | |
| # Deinitialization and cleanup. | |
| # Do not call torch.distributed.destroy_process_group, may be needed by other tests. | |
| def _deinit_distributed(): | |
| assert torch.distributed.is_initialized() == True | |
| torch.distributed.barrier() | |
| def test_nvtx_range(msg, suffix): | |
| # Track function execution | |
| execution_tracker = {'ranges': False} | |
| def _call_nvtx_range(): | |
| util.nvtx_range_push(msg, suffix) | |
| execution_tracker['ranges'] = True | |
| util.nvtx_range_pop(msg, suffix) | |
| # Test with NVTX disabled | |
| util.configure_nvtx_profiling(False) | |
| _call_nvtx_range() | |
| assert execution_tracker['ranges'] | |
| # Reset tracker | |
| execution_tracker['ranges'] = False | |
| # Test with NVTX enabled | |
| util.configure_nvtx_profiling(True) | |
| _call_nvtx_range() | |
| assert execution_tracker['ranges'] | |
| def test_nvtx_decorator(): | |
| # Track function execution | |
| execution_tracker = {'decorated': False, 'decorated_with_message': False} | |
| # Decorate while NVTX is disabled (the common import-time scenario). | |
| # The _nvtx_enabled flag must be checked at call time, not decoration time. | |
| util.configure_nvtx_profiling(False) | |
| def nvtx_decorated_function(): | |
| execution_tracker['decorated'] = True | |
| def nvtx_decorated_function_with_message(): | |
| execution_tracker['decorated_with_message'] = True | |
| # Call with NVTX disabled — should still execute the wrapped function | |
| nvtx_decorated_function() | |
| nvtx_decorated_function_with_message() | |
| assert all(execution_tracker.values()) | |
| # Reset tracker | |
| execution_tracker = {'decorated': False, 'decorated_with_message': False} | |
| # Enable NVTX *after* decoration — should pick up the new flag value | |
| util.configure_nvtx_profiling(True) | |
| nvtx_decorated_function() | |
| nvtx_decorated_function_with_message() | |
| assert all(execution_tracker.values()) | |
| # Reset tracker | |
| execution_tracker = {'decorated': False, 'decorated_with_message': False} | |
| # Disable NVTX again — should respect the toggled flag | |
| util.configure_nvtx_profiling(False) | |
| nvtx_decorated_function() | |
| nvtx_decorated_function_with_message() | |
| assert all(execution_tracker.values()) | |
| def test_check_param_hashes_across_dp_replicas(): | |
| world = int(os.getenv('WORLD_SIZE', '1')) | |
| rank = int(os.getenv('RANK', '0')) | |
| # Setup. | |
| _init_distributed(world, rank) | |
| Utils.initialize_model_parallel() | |
| model = torch.nn.Linear(100, 100, bias=False, device='cuda') | |
| # First check case where all replicas agree. | |
| model.weight.data.fill_(1.0) | |
| assert util.check_param_hashes_across_dp_replicas([model]) | |
| # Now check case where replica 0 disagrees with all other replicas. | |
| if rank == 0: | |
| model.weight.data.fill_(0.0) | |
| param_hashes_match = util.check_param_hashes_across_dp_replicas([model]) | |
| expected_param_hashes_match = rank == 0 | |
| assert param_hashes_match == expected_param_hashes_match | |
| # Teardown. | |
| _deinit_distributed() | |
| def test_cross_check_param_hashes_across_dp_replicas(): | |
| world = int(os.getenv('WORLD_SIZE', '1')) | |
| rank = int(os.getenv('RANK', '0')) | |
| # Setup. | |
| _init_distributed(world, rank) | |
| Utils.initialize_model_parallel() | |
| model = torch.nn.Linear(100, 100, bias=False, device='cuda') | |
| # First check case where all replicas agree. | |
| model.weight.data.fill_(1.0) | |
| assert util.check_param_hashes_across_dp_replicas([model], True) | |
| # Now check case where replica 0 disagrees with all other replicas. | |
| if rank == 0: | |
| model.weight.data.fill_(0.0) | |
| assert not util.check_param_hashes_across_dp_replicas([model], True) | |
| # Teardown. | |
| _deinit_distributed() | |
| def test_param_norm_linear(use_distributed_optimizer: bool): | |
| world = int(os.getenv('WORLD_SIZE', '1')) | |
| rank = int(os.getenv('RANK', '0')) | |
| # Setup: distributed, model, mock_args. | |
| _init_distributed(world, rank) | |
| Utils.initialize_model_parallel() | |
| model = torch.nn.Linear(100, 100, bias=False, dtype=torch.bfloat16, device='cuda') | |
| model.requires_grad_(True) | |
| model.weight.data.fill_(1.0) | |
| ddp_config = DistributedDataParallelConfig(use_distributed_optimizer=use_distributed_optimizer) | |
| # Use dummy TransformerConfig which doesn't trigger __post_init__ assertions. | |
| model = DistributedDataParallel( | |
| TransformerConfig(num_attention_heads=1, num_layers=1), ddp_config, model | |
| ) | |
| for param in model.parameters(): | |
| assert param.requires_grad | |
| mock_args = SimpleNamespace(bf16=True) | |
| with mock.patch('megatron.training.utils.get_args', new=lambda: mock_args): | |
| # Make sure norm is correct when `main_param` attribute is not available. | |
| assert training_util.calc_params_l2_norm( | |
| model, force_create_fp32_copy=False | |
| ) == pytest.approx(100.0) | |
| assert training_util.calc_params_l2_norm( | |
| model, force_create_fp32_copy=True | |
| ) == pytest.approx(100.0) | |
| # Make sure norm is correct when `main_param` attribute is available. | |
| optimizer_config = OptimizerConfig( | |
| bf16=True, use_distributed_optimizer=use_distributed_optimizer | |
| ) | |
| _ = get_megatron_optimizer(optimizer_config, [model]) | |
| for param in model.parameters(): | |
| assert hasattr(param, 'main_param') | |
| if use_distributed_optimizer: | |
| assert getattr(param, 'main_param_sharded', False) | |
| assert training_util.calc_params_l2_norm( | |
| model, force_create_fp32_copy=False | |
| ) == pytest.approx(100.0) | |
| assert training_util.calc_params_l2_norm( | |
| model, force_create_fp32_copy=True | |
| ) == pytest.approx(100.0) | |
| # Teardown. | |
| _deinit_distributed() | |
| def test_param_norm_moe(use_distributed_optimizer: bool): | |
| world = int(os.getenv('WORLD_SIZE', '1')) | |
| rank = int(os.getenv('RANK', '0')) | |
| # Setup: distributed, model, mock_args. | |
| _init_distributed(world, rank) | |
| Utils.initialize_model_parallel() | |
| transformer_config = TransformerConfig( | |
| num_layers=1, | |
| hidden_size=12, | |
| num_attention_heads=4, | |
| num_moe_experts=2, | |
| use_cpu_initialization=True, | |
| moe_token_dispatcher_type="alltoall", | |
| moe_router_topk=2, | |
| moe_aux_loss_coeff=0.01, | |
| moe_grouped_gemm=True, | |
| moe_ffn_hidden_size=128, | |
| add_bias_linear=False, | |
| bf16=True, | |
| ) | |
| submodules = get_submodules( | |
| get_gpt_layer_with_transformer_engine_submodules(num_experts=2, moe_grouped_gemm=True).mlp | |
| ) | |
| assert isinstance(submodules, MoESubmodules) | |
| model = MoELayer(transformer_config, submodules).to(device='cuda') | |
| model.requires_grad_(True) | |
| # Initialize the model with all 1.0 for weights. | |
| for param in model.parameters(): | |
| param.data.fill_(1.0) | |
| ddp_config = DistributedDataParallelConfig(use_distributed_optimizer=use_distributed_optimizer) | |
| model = DistributedDataParallel(transformer_config, ddp_config, model) | |
| for param in model.parameters(): | |
| assert param.requires_grad | |
| mock_args = SimpleNamespace(bf16=True) | |
| with mock.patch('megatron.training.utils.get_args', new=lambda: mock_args): | |
| # Make sure norm is correct when `main_param` attribute is not available. | |
| norm_no_fp32_copy = training_util.calc_params_l2_norm(model, force_create_fp32_copy=False) | |
| norm_fp32_copy = training_util.calc_params_l2_norm(model, force_create_fp32_copy=True) | |
| assert norm_no_fp32_copy == pytest.approx(norm_fp32_copy) | |
| # Make sure norm is correct when `main_param` attribute is available. | |
| optimizer_config = OptimizerConfig( | |
| bf16=True, use_distributed_optimizer=use_distributed_optimizer | |
| ) | |
| _ = get_megatron_optimizer(optimizer_config, [model]) | |
| for param in model.parameters(): | |
| # Only bf16/fp16 parameters get main_param attribute. | |
| # Router weights are always fp32, so they won't have main_param. | |
| if param.dtype in [torch.bfloat16, torch.float16]: | |
| assert hasattr(param, 'main_param') | |
| if use_distributed_optimizer: | |
| assert getattr(param, 'main_param_sharded', False) | |
| norm_no_fp32_copy = training_util.calc_params_l2_norm(model, force_create_fp32_copy=False) | |
| norm_fp32_copy = training_util.calc_params_l2_norm(model, force_create_fp32_copy=True) | |
| assert norm_no_fp32_copy == pytest.approx(norm_fp32_copy) | |
| # Teardown. | |
| _deinit_distributed() | |
| def test_straggler_detector(): | |
| world = int(os.getenv('WORLD_SIZE', '1')) | |
| rank = int(os.getenv('RANK', '0')) | |
| master = os.getenv('MASTER_ADDR', 'localhost') | |
| port = 65535 | |
| # Checks if the instance is disabled. | |
| def straggler_detector_disabled(): | |
| assert stimer.enabled == False | |
| # Checks if the instance is enabled. | |
| def straggler_detector_enabled(): | |
| assert stimer.enabled == True | |
| # Enable. | |
| def straggler_detector_enable(): | |
| if rank == 0: | |
| resp = req.urlopen(f"http://{master}:{port}").read().decode().split() | |
| assert resp[3] == "ON" | |
| # Call the report function, this will propagate the change. | |
| stimer.report() | |
| # Time an operation. | |
| def straggler_detector_timeit(): | |
| s = 2 # Sleep for 2 seconds. | |
| M = 20 | |
| K = 30 | |
| N = 40 | |
| mat1 = torch.randn(M, K, device='cuda') | |
| mat2 = torch.randn(K, N, device='cuda') | |
| # batch_data. | |
| with stimer(bdata=True): | |
| time.sleep(s) | |
| # GEMM. | |
| with stimer: | |
| res = torch.matmul(mat1, mat2) | |
| delta, batch_delta, _, _, _, _ = stimer.elapsed() | |
| assert delta > 0.0 | |
| assert batch_delta >= s | |
| # Test function to raise ValueError | |
| def straggler_value_error(): | |
| raise ValueError("Exception value raised") | |
| # Check that exception is not suppressed. | |
| def straggler_detector_exception_propagate(): | |
| # batch_data | |
| with pytest.raises(ZeroDivisionError): | |
| with stimer(bdata=True): | |
| x = 1 / 0 | |
| # non-batch-data | |
| with pytest.raises(ValueError, match=r".* value .*"): | |
| with stimer(): | |
| straggler_value_error() | |
| # Reporting. | |
| def straggler_detector_report(): | |
| s = 2 # Sleep for 2 seconds. | |
| N = 20 | |
| P = 30 | |
| M = 40 | |
| mat1 = torch.randn(N, P, device='cuda') | |
| mat2 = torch.randn(P, M, device='cuda') | |
| tfp = (N * M) * (2 * P - 1) # Theoretical. | |
| iter = 10 # Mock. | |
| # batch_data. | |
| with stimer(bdata=True): | |
| time.sleep(s) | |
| # GEMM. | |
| with stimer: | |
| res = torch.matmul(mat1, mat2) | |
| r = stimer.report(total_flops=tfp, log_interval=iter) | |
| rb = True if rank == 0 else False | |
| assert r == rb | |
| # Start test. | |
| # Setup. | |
| _init_distributed(world, rank) | |
| # Create a straggler_detector with enabled set to false. | |
| stimer = util.StragglerDetector() | |
| stimer.configure(world, rank, enabled=False, port=port) | |
| # Check if configuration was success. | |
| assert stimer.configured == True | |
| # Check if the instance is in disabled state. | |
| straggler_detector_disabled() | |
| # Enable it now, must call report. | |
| straggler_detector_enable() | |
| # Check if all ranks have straggler detector enabled. | |
| straggler_detector_enabled() | |
| # Time some operation. | |
| straggler_detector_timeit() | |
| # Report only from rank 0. | |
| straggler_detector_report() | |
| # Check that exception is not suppressed. | |
| straggler_detector_exception_propagate() | |
| util.StragglerDetector._configured = False | |
| # Teardown. | |
| _deinit_distributed() | |
| class TestGetWorldSizeSafe: | |
| """Test get_world_size_safe function.""" | |
| def test_initialized_torch_distributed(self, mock_get_world_size, mock_is_initialized): | |
| """Test get_world_size_safe when torch.distributed is initialized.""" | |
| mock_is_initialized.return_value = True | |
| mock_get_world_size.return_value = 4 | |
| result = safe_get_world_size() | |
| assert result == 4 | |
| mock_is_initialized.assert_called_once() | |
| mock_get_world_size.assert_called_once() | |
| def test_uninitialized_torch_distributed_with_env_var(self, mock_is_initialized): | |
| """Test get_world_size_safe when torch.distributed is not initialized but WORLD_SIZE env var exists.""" | |
| mock_is_initialized.return_value = False | |
| result = safe_get_world_size() | |
| assert result == 8 | |
| mock_is_initialized.assert_called_once() | |
| def test_uninitialized_torch_distributed_no_env_var(self, mock_is_initialized): | |
| """Test get_world_size_safe when torch.distributed is not initialized and no WORLD_SIZE env var.""" | |
| mock_is_initialized.return_value = False | |
| result = safe_get_world_size() | |
| assert result == 1 | |
| mock_is_initialized.assert_called_once() | |
| def test_invalid_world_size_env_var(self, mock_is_initialized): | |
| """Test get_world_size_safe with invalid WORLD_SIZE environment variable.""" | |
| mock_is_initialized.return_value = False | |
| with pytest.raises(ValueError): | |
| safe_get_world_size() | |
| class TestGetRankSafe: | |
| """Test safe_get_rank function.""" | |
| def test_uninitialized_torch_distributed_with_rank_env_var(self, mock_is_initialized): | |
| """Test safe_get_rank when torch.distributed is not initialized but RANK env var exists.""" | |
| mock_is_initialized.return_value = False | |
| result = safe_get_rank() | |
| assert result == 9 | |
| mock_is_initialized.assert_called_once() | |
| def test_invalid_rank_env_var_should_raise_value_error(self, mock_is_initialized): | |
| """Test safe_get_rank with invalid RANK environment variable.""" | |
| mock_is_initialized.return_value = False | |
| with pytest.raises(ValueError): | |
| safe_get_rank() | |
| class TestGetLocalRankPreinit: | |
| """Test get_local_rank_preinit function.""" | |
| def test_uses_local_rank_env_var(self): | |
| assert get_local_rank_preinit() == 3 | |
| def test_local_rank_takes_precedence_over_slurm(self): | |
| assert get_local_rank_preinit() == 2 | |
| def test_falls_back_to_slurm_localid(self): | |
| assert get_local_rank_preinit() == 6 | |
| def test_defaults_to_zero_with_warning(self): | |
| with pytest.warns(UserWarning, match="Could not determine local rank"): | |
| assert get_local_rank_preinit() == 0 | |
| class TestSingleGroupReductionHelpers: | |
| """The optional ``group=`` on the reduction helpers, exercised with a HyperCommGrid-derived | |
| process group (no ``parallel_state`` init — the MIMO use case) plus a default→mpu fallback.""" | |
| def _ranks(group): | |
| return torch.distributed.get_process_group_ranks(group) | |
| def test_explicit_grid_group(self): | |
| """Helpers reduce correctly over a group built from a HyperCommGrid, no parallel_state.""" | |
| from megatron.core.hyper_comm_grid import HyperCommGrid | |
| from megatron.training.utils.common_utils import ( | |
| average_losses_across_data_parallel_group, | |
| logical_and_across_model_parallel_group, | |
| reduce_max_stat_across_model_parallel_group, | |
| ) | |
| Utils.initialize_distributed() # torch.distributed only; NOT initialize_model_parallel | |
| world = torch.distributed.get_world_size() | |
| rank = torch.distributed.get_rank() | |
| # tp=2 over the world: "tp" groups stand in for a model-parallel group, "dp" for data. | |
| grid = HyperCommGrid([2, world // 2], ["tp", "dp"], backend="nccl") | |
| grid.create_pg(["tp"]) | |
| grid.create_pg(["dp"]) | |
| mp_group, dp_group = grid.get_pg("tp"), grid.get_pg("dp") | |
| mp_ranks, dp_ranks = self._ranks(mp_group), self._ranks(dp_group) | |
| try: | |
| # reduce_max: MAX over the grid mp group. | |
| assert reduce_max_stat_across_model_parallel_group( | |
| float(rank), group=mp_group | |
| ) == float(max(mp_ranks)) | |
| # logical_and: True iff every member is True (only the lowest mp rank passes True). | |
| flag = rank == min(mp_ranks) | |
| expected_and = all(r == min(mp_ranks) for r in mp_ranks) | |
| assert logical_and_across_model_parallel_group(flag, group=mp_group) is expected_and | |
| # average: SUM-then-divide over the grid dp group -> mean of member ranks. | |
| loss = torch.tensor(float(rank), device=torch.cuda.current_device()) | |
| out = average_losses_across_data_parallel_group([loss], group=dp_group) | |
| torch.testing.assert_close( | |
| out.cpu(), torch.tensor([sum(dp_ranks) / len(dp_ranks)], dtype=torch.float32) | |
| ) | |
| finally: | |
| grid.destroy() | |
| def test_default_falls_back_to_mpu(self): | |
| """With no ``group=``, helpers read the mpu global (back-compat for non-MIMO callers).""" | |
| from megatron.core import parallel_state as mpu | |
| from megatron.training.utils.common_utils import reduce_max_stat_across_model_parallel_group | |
| Utils.initialize_model_parallel(tensor_model_parallel_size=2) | |
| rank = torch.distributed.get_rank() | |
| explicit = reduce_max_stat_across_model_parallel_group( | |
| float(rank), group=mpu.get_model_parallel_group() | |
| ) | |
| default = reduce_max_stat_across_model_parallel_group(float(rank)) | |
| assert default == explicit | |
| Utils.destroy_model_parallel() | |
| class TestTrainStepReductionThreading: | |
| """train_step's reductions over a per-module ProcessGroupCollection's mp/pp/dp_cp groups.""" | |
| def _ranks(group): | |
| return torch.distributed.get_process_group_ranks(group) | |
| def test_grid_threaded_reductions(self): | |
| from megatron.core.hyper_comm_grid import HyperCommGrid | |
| from megatron.core.pipeline_parallel.utils import is_pp_last_stage | |
| from megatron.training.utils.common_utils import ( | |
| logical_and_across_model_parallel_group, | |
| reduce_max_stat_across_model_parallel_group, | |
| ) | |
| Utils.initialize_distributed() # torch.distributed only; NOT initialize_model_parallel | |
| rank = torch.distributed.get_rank() | |
| # tp=2,pp=2,dp=2 over the world: mp == tp+pp, dp_cp == dp. | |
| grid = HyperCommGrid([2, 2, 2], ["tp", "pp", "dp"], backend="nccl") | |
| grid.create_pg(["tp", "pp"]) | |
| grid.create_pg(["pp"]) | |
| grid.create_pg(["dp"]) | |
| mp_group = grid.get_pg(["tp", "pp"]) | |
| pp_group = grid.get_pg(["pp"]) | |
| dp_cp_group = grid.get_pg(["dp"]) | |
| mp_ranks = self._ranks(mp_group) | |
| pp_ranks = self._ranks(pp_group) | |
| dp_cp_ranks = self._ranks(dp_cp_group) | |
| try: | |
| # reduce_max (grad_norm / num_zeros): MAX over the grid mp group. | |
| assert reduce_max_stat_across_model_parallel_group( | |
| float(rank), group=mp_group | |
| ) == float(max(mp_ranks)) | |
| # logical_and (update_successful): True iff every mp member is True. | |
| flag = rank != min(mp_ranks) # one rank dissents -> AND is False on the whole group. | |
| assert logical_and_across_model_parallel_group(flag, group=mp_group) is False | |
| # is_pp_last_stage: True only on the highest rank of the pp group. | |
| assert is_pp_last_stage(pp_group) is (rank == max(pp_ranks)) | |
| # per-key loss all-reduce: SUM over the grid dp_cp group. | |
| val = torch.tensor([float(rank), 1.0], device=torch.cuda.current_device()) | |
| torch.distributed.all_reduce(val, group=dp_cp_group) | |
| expected = torch.tensor( | |
| [float(sum(dp_cp_ranks)), float(len(dp_cp_ranks))], dtype=torch.float32 | |
| ) | |
| torch.testing.assert_close(val.cpu(), expected) | |
| finally: | |
| grid.destroy() | |
Xet Storage Details
- Size:
- 28.4 kB
- Xet hash:
- 993ed2cb221283b005d8d3747e297bf00bb2fa9a2eae9625082c7e0d9794af78
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.