随机种子复现模型
测试环境:
2080ti, cpu2.9GHz, 8core
python3.6.12 torch1.4.0
常见的博客中提到的设置如下
def _init_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) #multi-gpu
os.environ['PYTHONHASHSEED'] = str(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.enabled = False
笔者尝试过后,发现真正有用的是DataLoader的num_worker设置为0或者1以及torch.backends.cudnn.enabled = False,其他博客中也有人提到
只用num_worker = 0的现象类似于上述。
有的博客提到num_worker > 1的时候需在DataLoader中定义
def _init_fn(worker_id):
np.random.seed(int(seed))
trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True, worker_init_fn=_init_fn)
笔者尝试后发现没有作用,一个可能原因是当重新定义相同seed时候,随机序列是reset的效果
PS:这里复现只是连续重复运行几次结果一样,不连续的结果又不一样,原因未知。