文档首页/ AI开发平台ModelArts/ 故障排除/ 训练作业/ GPU相关问题/ 日志提示“RuntimeError: Cannot re-initialize CUDA in forked subprocess”
更新时间:2024-10-30 GMT+08:00

日志提示“RuntimeError: Cannot re-initialize CUDA in forked subprocess”

问题现象

在使用pytorch启动多进程的时候,出现如下报错:
RuntimeError: Cannot re-initialize CUDA in forked subprocess

原因分析

出现该问题的可能原因如下:

multiprocessing启动方式有误。

处理方法

可以参考官方文档,如下:
"""run.py:"""
#!/usr/bin/env python
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

def run(rank, size):
    """ Distributed function to be implemented later. """
    pass

def init_process(rank, size, fn, backend='gloo'):
    """ Initialize the distributed environment. """
    os.environ['MASTER_ADDR'] = '127.0.0.1'
    os.environ['MASTER_PORT'] = '29500'
    dist.init_process_group(backend, rank=rank, world_size=size)
    fn(rank, size)


if __name__ == "__main__":
    size = 2
    processes = []
    mp.set_start_method("spawn")
    for rank in range(size):
        p = mp.Process(target=init_process, args=(rank, size, run))
        p.start()
        processes.append(p)

    for p in processes:
        p.join()

建议与总结

在创建训练作业前,推荐您先使用ModelArts开发环境调试训练代码,避免代码迁移过程中的错误。