|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Unit tests for pretrain module process group cleanup.""" |
| 16 | + |
| 17 | +from unittest.mock import patch |
| 18 | + |
| 19 | +from megatron.bridge.training.pretrain import _maybe_destroy_process_group |
| 20 | + |
| 21 | + |
| 22 | +class TestDestroyProcessGroupIfNeeded: |
| 23 | + """Test process group destruction logic.""" |
| 24 | + |
| 25 | + @patch("megatron.bridge.training.pretrain.dist") |
| 26 | + def test_destroy_when_should_destroy_and_initialized(self, mock_dist): |
| 27 | + """Test process group is destroyed when both conditions are met.""" |
| 28 | + mock_dist.is_initialized.return_value = True |
| 29 | + |
| 30 | + _maybe_destroy_process_group(should_destroy=True) |
| 31 | + |
| 32 | + mock_dist.barrier.assert_called_once() |
| 33 | + mock_dist.destroy_process_group.assert_called_once() |
| 34 | + |
| 35 | + @patch("megatron.bridge.training.pretrain.dist") |
| 36 | + def test_no_destroy_when_should_not_destroy(self, mock_dist): |
| 37 | + """Test no destruction when should_destroy is False.""" |
| 38 | + mock_dist.is_initialized.return_value = True |
| 39 | + |
| 40 | + _maybe_destroy_process_group(should_destroy=False) |
| 41 | + |
| 42 | + mock_dist.barrier.assert_not_called() |
| 43 | + mock_dist.destroy_process_group.assert_not_called() |
| 44 | + |
| 45 | + @patch("megatron.bridge.training.pretrain.dist") |
| 46 | + def test_no_destroy_when_not_initialized(self, mock_dist): |
| 47 | + """Test no destruction when process group is not initialized.""" |
| 48 | + mock_dist.is_initialized.return_value = False |
| 49 | + |
| 50 | + _maybe_destroy_process_group(should_destroy=True) |
| 51 | + |
| 52 | + mock_dist.barrier.assert_not_called() |
| 53 | + mock_dist.destroy_process_group.assert_not_called() |
| 54 | + |
| 55 | + @patch("megatron.bridge.training.pretrain.dist") |
| 56 | + def test_no_destroy_when_neither_condition_met(self, mock_dist): |
| 57 | + """Test no destruction when both conditions are false.""" |
| 58 | + mock_dist.is_initialized.return_value = False |
| 59 | + |
| 60 | + _maybe_destroy_process_group(should_destroy=False) |
| 61 | + |
| 62 | + mock_dist.barrier.assert_not_called() |
| 63 | + mock_dist.destroy_process_group.assert_not_called() |
0 commit comments