pytorch如何实现可复现性

本文介绍了一种确保PyTorch实验结果可复现的方法,通过固定随机种子来减少不同运行间的差异,包括对CPU和GPU的随机数生成器进行设置,并关闭cuDNN的benchmark模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

参考资料:

  1. https://blog.youkuaiyun.com/u010589524/article/details/89371919
  2. 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.

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值