|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +# pyre-strict |
| 8 | + |
| 9 | +import os |
| 10 | +import shutil |
| 11 | +import tempfile |
| 12 | +import unittest |
| 13 | + |
| 14 | +import torch.distributed as dist |
| 15 | +from torchtnt.utils import init_from_env |
| 16 | +from torchtnt.utils.checkpoint import get_checkpoint_dirpaths |
| 17 | +from torchtnt.utils.distributed import get_global_rank, spawn_multi_process |
| 18 | +from torchtnt.utils.test_utils import skip_if_not_distributed, skip_if_not_gpu |
| 19 | + |
| 20 | + |
| 21 | +class TestCheckpointUtilsGPU(unittest.TestCase): |
| 22 | + |
| 23 | + @skip_if_not_distributed |
| 24 | + @skip_if_not_gpu |
| 25 | + def test_get_checkpoint_dirpaths_distributed(self) -> None: |
| 26 | + spawn_multi_process( |
| 27 | + 2, |
| 28 | + "nccl", |
| 29 | + self._test_get_checkpoint_dirpaths, |
| 30 | + ) |
| 31 | + |
| 32 | + @staticmethod |
| 33 | + def _test_get_checkpoint_dirpaths() -> None: |
| 34 | + """ |
| 35 | + Tests retrieving checkpoint directories from a given root directory |
| 36 | + using NCCL on GPUs with custom state for pickling. |
| 37 | + """ |
| 38 | + init_from_env() |
| 39 | + paths = [ |
| 40 | + "epoch_0_step_10", |
| 41 | + "epoch_1_step_10_val_loss=10.5", |
| 42 | + "epoch_2_step_10", |
| 43 | + "epoch_0_step_5", |
| 44 | + "epoch_0_step_6_acc=0.03", |
| 45 | + "epoch_0_step_3", |
| 46 | + ] |
| 47 | + |
| 48 | + if get_global_rank() == 0: |
| 49 | + temp_dir = tempfile.mkdtemp() |
| 50 | + for path in paths: |
| 51 | + os.mkdir(os.path.join(temp_dir, path)) |
| 52 | + else: |
| 53 | + temp_dir = None |
| 54 | + |
| 55 | + tc = unittest.TestCase() |
| 56 | + # Only rank 0 will know about temp_dir |
| 57 | + if get_global_rank() != 0: |
| 58 | + tc.assertIsNone(temp_dir) |
| 59 | + |
| 60 | + ckpt_dirpaths = get_checkpoint_dirpaths( |
| 61 | + temp_dir, process_group=dist.group.WORLD |
| 62 | + ) |
| 63 | + |
| 64 | + # Broadcast temp_dir to verify successful execution |
| 65 | + temp_dir = [temp_dir] if get_global_rank() == 0 else [None] |
| 66 | + dist.broadcast_object_list(temp_dir, src=0, group=dist.group.WORLD) |
| 67 | + temp_dir = temp_dir[0] |
| 68 | + tc.assertIsNotNone(temp_dir) |
| 69 | + |
| 70 | + tc.assertEqual( |
| 71 | + {str(x) for x in ckpt_dirpaths}, |
| 72 | + {os.path.join(temp_dir, path) for path in paths}, |
| 73 | + ) |
| 74 | + |
| 75 | + if get_global_rank() == 0: |
| 76 | + shutil.rmtree(temp_dir) |
0 commit comments