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

Use pytorch lightning's seed everything to set seed #1151

Merged
merged 4 commits into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 2 additions & 3 deletions scvi/_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from pathlib import Path
from typing import Union

import numpy as np
import pytorch_lightning as pl
import torch
from rich.console import Console
from rich.logging import RichHandler
Expand Down Expand Up @@ -140,10 +140,9 @@ def seed(self) -> int:
@seed.setter
def seed(self, seed: int):
"""Random seed for torch and numpy."""
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
pl.utilities.seed.seed_everything(seed)
self._seed = seed

@property
Expand Down
18 changes: 18 additions & 0 deletions tests/models/test_lightning.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import torch

import scvi
from scvi.data import synthetic_iid
from scvi.model import SCVI
from scvi.train._callbacks import SaveBestState
Expand All @@ -9,3 +12,18 @@ def test_save_best_state_callback(save_path):
model = SCVI(adata, n_latent=n_latent)
callbacks = [SaveBestState(verbose=True)]
model.train(3, check_val_every_n_epoch=1, train_size=0.5, callbacks=callbacks)


def test_set_seed(save_path):
scvi.settings.seed = 1
n_latent = 5
adata = synthetic_iid()
model1 = SCVI(adata, n_latent=n_latent)
model1.train(1)
scvi.settings.seed = 1
model2 = SCVI(adata, n_latent=n_latent)
model2.train(1)
assert torch.equal(
model1.module.z_encoder.encoder.fc_layers[0][0].weight,
model2.module.z_encoder.encoder.fc_layers[0][0].weight,
)