Hi,
So, as far as I understand there are basically four possible seeds to be set in a DeepChem project, depending on your backend.
For this I created this nifty function. It is rather self explanatory, but it basically allows you to set a random seed for these four random number generators. Please do let me know if I miss a seed in the function.
def set_seed(seed, tensorflow=True, pytorch=True):
"""
Sets the random seed for various libraries (NumPy, TensorFlow, PyTorch, and Python's random module).
Parameters:
- seed (int): The random seed value to set for the libraries.
- tensorflow (bool, optional): Set the seed for TensorFlow if True. Defaults to True.
- pytorch (bool, optional): Set the seed for PyTorch if True. Defaults to True.
Note: Assumes libraries are already imported when setting their respective seeds.
"""
# Set seed for TensorFlow
try:
if tensorflow:
tf.random.set_seed(seed)
except:
print("Please import Tensorflow as tf to set its seed.")
# Set seed for PyTorch
try:
if pytorch:
torch.manual_seed(seed)
# Set seed for PyTorch's CUDA and enforce deterministic behavior
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
except:
print("Please import PyTorch to set its seed.")
# Set seed for NumPy and Python's random module
try:
np.random.seed(seed)
random.seed(seed)
except:
print("You must import numpy as np and random to set up seeds.")
# Example
import torch
import random
import tensorflow as tf
import numpy as np
set_seed(seed=1, tensorflow=True, pytorch=True)
Best regards
Jacob, University of Copenhagen