# Set PyTorch seed
torch.manual_seed(seed)
# Set NumPy seed
np.random.seed(seed)
# Set Python random seed
random.seed(seed)
# Ensure CUDA determinism (if used)
torch.backends.cudnn.deterministic=True
torch.backends.cudnn.benchmark=False
# Set seed
set_seed(42)
# Generate random data
x = torch.randn(3,4)
print(x)
Output result:
tensor([[ 0.3367, 0.1288, 0.2345, 0.2303], [-1.1229, -0.1863, 0.1735, -0.5524], [ 0.6351, -0.2582, 0.4602, -0.5270]])
To fully guarantee reproducibility, you need to set the seeds for PyTorch, NumPy, and Python random simultaneously.
Pytorch torch Reference Manual