pytorch trainloader遇到的多进程问题

pytorch中尝试用多进程加载训练数据集,源码如下:

trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=3)

结果报错:

RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

从报错信息可以看到,当前进程在运行可执行代码时,产生了一个新进程。这可能意味着您没有使用fork来启动子进程或者是未在主模块中正确使用。后来经过查阅发现了原因,因为windows系统下默认用spawn方法部署多线程,如果代码没有受到__main__模块的保护,新进程都认为是要再次运行的代码,将尝试再次执行与父进程相同的代码,生成另一个进程,依此类推,直到程序崩溃。

解决方法很简单,把调用多进程的代码放到__main__模块下即可。

if __name__ == '__main__':
    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
    trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=3)

 

你可能感兴趣的:(pytorch)