在pytorch版本固定、其他软硬件平台固定、问题固定时(也就是在固定的机器上跑同一个实验时),可以使用如下代码。如果pytorch版本不同、各种软硬件平台不同,实验结果的可复现性是不能被完全保证的。
import torch
import random
import numpy as np
def set_seed(seed=9699): # seed的数值可以随意设置,本人不清楚有没有推荐数值
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
#根据文档,torch.manual_seed(seed)应该已经为所有设备设置seed
#但是torch.cuda.manual_seed(seed)在没有gpu时也可调用,这样写没什么坏处
torch.cuda.manual_seed(seed)
#cuDNN在使用deterministic模式时(下面两行),可能会造成性能下降(取决于model)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
参考资料:
- https://blog.youkuaiyun.com/u010589524/article/details/89371919
- https://pytorch.org/docs/stable/notes/randomness.html
特别是:
You can use torch.manual_seed() to seed the RNG for all devices (both CPU and CUDA)
torch.cuda.manual_seed(seed) sets the seed for generating random numbers for the current GPU. It’s safe to call this function if CUDA is not available; in that case, it is silently ignored.