【问题标题】:How to set random seed when it is in distributed training in PyTorch?在 PyTorch 的分布式训练中如何设置随机种子?
【发布时间】:2020-09-17 16:31:51
【问题描述】:

现在我正在使用torch.distributed 训练模型,但我不确定如何设置随机种子。例如,这是我当前的代码:

def main():
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    cudnn.enabled = True
    cudnn.benchmark = True
    cudnn.deterministic = True 

    mp.spawn(main_worker, nprocs=args.ngpus, args=(args,))

我应该移动

    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed(args.seed)

    cudnn.enabled = True
    cudnn.benchmark = True
    cudnn.deterministic = True 

进入函数main_worker() 以确保每个进程都有正确的种子和cudnn 设置?顺便说一句,我试过这个,这种行为会使训练慢 2 倍,这让我很困惑。

非常感谢您的帮助!

【问题讨论】:

  • 使用torch.cuda.manual_seed_all() 而不是torch.cuda.manual_seed
  • 感谢您的评论!但是我可以在每个进程中使用 torch.cuda.manual_seed() 吗?(每个进程将使用单个 GPU)

标签: python parallel-processing pytorch distributed python-parallel


【解决方案1】:

衍生的子进程不会继承您在父进程中手动设置的种子,因此您需要在main_worker 函数中设置种子。

同样的逻辑适用于cudnn.benchmarkcudnn.deterministic,所以如果你想使用它们,你也必须在main_worker 中设置它们。如果您想验证这一点,您可以在每个过程中打印它们的值。

cudnn.benchmark = True 尝试通过对某些操作的各种实现进行基准测试(例如available convolution algorithms)来为您的模型找到最佳算法。这需要时间来找到最佳算法,但一旦完成,进一步的迭代可能会更快。被确定为最佳的算法仅适用于所使用的特定输入大小。如果在下一次迭代中您有不同的输入大小,则需要再次运行基准测试,以确定该特定输入大小的最佳算法,这可能与第一个输入大小不同。

我假设您的输入大小不同,这可以解释速度变慢,因为在父进程中设置基准时未使用基准。 cudnn.benchmark = True 仅应在您的输入大小固定时使用。

cudnn.determinstic = True 也可能对性能产生负面影响,因为某些非确定性的底层操作需要替换为确定性版本,这往往会更慢,否则确定性版本将用于第一,但对性能的影响不应该太大。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-08-28
    • 2016-11-12
    • 2020-02-03
    • 2020-03-18
    相关资源
    最近更新 更多