Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Check environ before selecting a seed to prevent warning message #4743

Merged
merged 16 commits into from
Jan 12, 2021
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions pytorch_lightning/utilities/seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import numpy as np
import torch

from pytorch_lightning import _logger as log
from pytorch_lightning.utilities import rank_zero_warn


def seed_everything(seed: Optional[int] = None) -> int:
Expand All @@ -41,16 +41,14 @@ def seed_everything(seed: Optional[int] = None) -> int:

try:
if seed is None:
seed = os.environ.get("PL_GLOBAL_SEED", _select_seed_randomly(min_seed_value, max_seed_value))
awaelchli marked this conversation as resolved.
Show resolved Hide resolved
seed = os.environ.get("PL_GLOBAL_SEED")
seed = int(seed)
except (TypeError, ValueError):
seed = _select_seed_randomly(min_seed_value, max_seed_value)
rank_zero_warn(f"No correct seed found, seed set to {seed}")
Comment on lines 47 to +48
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
seed = _select_seed_randomly(min_seed_value, max_seed_value)
rank_zero_warn(f"No correct seed found, seed set to {seed}")
seed_new = _select_seed_randomly(min_seed_value, max_seed_value)
rank_zero_warn(f"No correct seed `{seed}` found, seed set to `{seed_new}`")
seed = seed_new


if (seed > max_seed_value) or (seed < min_seed_value):
log.warning(
f"{seed} is not in bounds, \
numpy accepts from {min_seed_value} to {max_seed_value}"
)
if not (min_seed_value <= seed <= max_seed_value):
rank_zero_warn(f"{seed} is not in bounds, numpy accepts from {min_seed_value} to {max_seed_value}")
seed = _select_seed_randomly(min_seed_value, max_seed_value)

os.environ["PL_GLOBAL_SEED"] = str(seed)
SeanNaren marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -62,6 +60,4 @@ def seed_everything(seed: Optional[int] = None) -> int:


def _select_seed_randomly(min_seed_value: int = 0, max_seed_value: int = 255) -> int:
seed = random.randint(min_seed_value, max_seed_value)
log.warning(f"No correct seed found, seed set to {seed}")
return seed
return random.randint(min_seed_value, max_seed_value)
68 changes: 68 additions & 0 deletions tests/utilities/test_seed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import os

import pytest

import pytorch_lightning.utilities.seed as seed_utils


def test_seed_stays_same_with_multiple_seed_everything_calls():
SeanNaren marked this conversation as resolved.
Show resolved Hide resolved
"""
Ensure that after the initial seed everything,
the seed stays the same for the same run.
"""
if "PL_GLOBAL_SEED" in os.environ:
del os.environ["PL_GLOBAL_SEED"]

with pytest.warns(UserWarning, match="No correct seed found"):
seed_utils.seed_everything()
initial_seed = os.environ.get("PL_GLOBAL_SEED")

with pytest.warns(None) as record:
seed_utils.seed_everything()
assert not record # does not warn
seed = os.environ.get("PL_GLOBAL_SEED")

assert initial_seed == seed
SeanNaren marked this conversation as resolved.
Show resolved Hide resolved
del os.environ["PL_GLOBAL_SEED"]


def test_correct_seed_with_environment_variable(monkeypatch):
"""
Ensure that the PL_GLOBAL_SEED environment is read
"""
if "PL_GLOBAL_SEED" in os.environ:
del os.environ["PL_GLOBAL_SEED"]
expected = 2020
monkeypatch.setenv("PL_GLOBAL_SEED", str(expected))
assert seed_utils.seed_everything() == expected
del os.environ["PL_GLOBAL_SEED"]
SeanNaren marked this conversation as resolved.
Show resolved Hide resolved


def test_invalid_seed(monkeypatch):
"""
Ensure that we still fix the seed even if an invalid seed is given
"""
if "PL_GLOBAL_SEED" in os.environ:
del os.environ["PL_GLOBAL_SEED"]
expected = 123
monkeypatch.setenv("PL_GLOBAL_SEED", "invalid")
monkeypatch.setattr(seed_utils, "_select_seed_randomly", lambda *_: expected)
with pytest.warns(UserWarning, match="No correct seed found"):
seed = seed_utils.seed_everything()
assert seed == expected
del os.environ["PL_GLOBAL_SEED"]


@pytest.mark.parametrize("seed", (10e9, -10e9))
def test_out_of_bounds_seed(monkeypatch, seed):
"""
Ensure that we still fix the seed even if an out-of-bounds seed is given
"""
if "PL_GLOBAL_SEED" in os.environ:
del os.environ["PL_GLOBAL_SEED"]
expected = 123
monkeypatch.setattr(seed_utils, "_select_seed_randomly", lambda *_: expected)
with pytest.warns(UserWarning, match="is not in bounds"):
actual = seed_utils.seed_everything(seed)
assert actual == expected
del os.environ["PL_GLOBAL_SEED"]