0
点赞
收藏
分享

微信扫一扫

Pytorch 随机种子的设置

def set_random_seed(seed, deterministic=False):
    """Set random seed.

    Args:
        seed (int): Seed to be used.
        deterministic (bool): Whether to set the deterministic option for
            CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
            to True and `torch.backends.cudnn.benchmark` to False.
            Default: False.
    """
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
	
	# 这部分我之前没有设置,所以导致了网络训练具有随机性
    if deterministic:
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False 

torch.backends.cudnn.benchmark = False 解释

CUDA 卷积操作使用的 cuDNN 库可能是跨应用程序多次执行的不确定性来源。当使用一组新的大小参数调用 cuDNN 卷积时,可选功能可以运行多个卷积算法,对它们进行基准测试以找到最快的一个。然后,最快的算法将在剩下的过程中一致地用于相应的大小参数集。由于基准测试噪音和不同的硬件,基准测试可能会在后续运行中选择不同的算法,即使是在同一台机器上

torch.backends.cudnn.deterministic = True 解释

虽然禁用 CUDA 卷积基准测试(如上所述)可确保每次运行应用程序时 CUDA 选择相同的算法,但该算法本身可能是不确定的,除非设置了 torch.use_deterministic_algorithms(True)torch.backends.cudnn.deterministic = True . 后一个设置仅控制此行为,与 torch.use_deterministic_algorithms()不同,后者将使其他 PyTorch 操作也具有确定性行为。

reference

https://pytorch.org/docs/stable/notes/randomness.html

举报

相关推荐

0 条评论