|
| 1 | +# Copyright The PyTorch Lightning team. |
| 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 | +import os |
| 15 | +from typing import Mapping |
| 16 | +from unittest import mock |
| 17 | + |
| 18 | +import pytest |
| 19 | + |
| 20 | + |
| 21 | +@pytest.mark.parametrize("env_vars", [{"RANK": "0"}, {"SLURM_PROCID": "0"}]) |
| 22 | +def test_rank_zero_known_cluster_envs(env_vars: Mapping[str, str]): |
| 23 | + """ Test that SLURM environment variables are properly checked for rank_zero_only. """ |
| 24 | + from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only |
| 25 | + rank_zero_only.rank = _get_rank() |
| 26 | + |
| 27 | + with mock.patch.dict(os.environ, env_vars): |
| 28 | + from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only |
| 29 | + rank_zero_only.rank = _get_rank() |
| 30 | + |
| 31 | + @rank_zero_only |
| 32 | + def foo(): # The return type is optional because on non-zero ranks it will not be called |
| 33 | + return 1 |
| 34 | + |
| 35 | + x = foo() |
| 36 | + assert x == 1 |
| 37 | + |
| 38 | + |
| 39 | +@pytest.mark.parametrize("rank_key,rank", [ |
| 40 | + ("RANK", "1"), |
| 41 | + ("SLURM_PROCID", "2"), |
| 42 | + ("LOCAL_RANK", "3"), |
| 43 | +]) |
| 44 | +def test_rank_zero_none_set(rank_key, rank): |
| 45 | + """ Test that function is not called when rank environment variables are not global zero. """ |
| 46 | + |
| 47 | + with mock.patch.dict(os.environ, {rank_key: rank}): |
| 48 | + from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only |
| 49 | + rank_zero_only.rank = _get_rank() |
| 50 | + |
| 51 | + @rank_zero_only |
| 52 | + def foo(): |
| 53 | + return 1 |
| 54 | + |
| 55 | + x = foo() |
| 56 | + assert x is None |
0 commit comments