我正在尝试在pytorch
中使用Python的多处理Pool
方法来处理图像。这是代码:
from multiprocessing import Process, Pool
from torch.autograd import Variable
import numpy as np
from scipy.ndimage import zoom
def get_pred(args):
img = args[0]
scale = args[1]
scales = args[2]
img_scale = zoom(img.numpy(),
(1., 1., scale, scale),
order=1,
prefilter=False,
mode='nearest')
# feed input data
input_img = Variable(torch.from_numpy(img_scale),
volatile=True).cuda()
return input_img
scales = [1,2,3,4,5]
scale_list = []
for scale in scales:
scale_list.append([img,scale,scales])
multi_pool = Pool(processes=5)
predictions = multi_pool.map(get_pred,scale_list)
multi_pool.close()
multi_pool.join()
我遇到了这个错误:
`RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method
`在这一行中:
predictions = multi_pool.map(get_pred,scale_list)
谁能告诉我我做错了什么?
如Pytorch文档中所述,处理多处理的最佳实践是使用torch.multiprocessing
代替multiprocessing
。
请注意,在Python 3中仅支持spawn
或forkserver
作为开始方法,在Python 3中仅支持CUDA张量。
没有触摸您的代码,解决您遇到的错误的解决方法是替换
from multiprocessing import Process, Pool
with:
from torch.multiprocessing import Pool, Process, set_start_method
try:
set_start_method('spawn')
except RuntimeError:
pass
我建议您阅读多处理模块的文档,尤其是本节。您将必须通过调用set_start_method
来更改子过程的创建方式。取自那些引用的文档:
import multiprocessing as mp
def foo(q):
q.put('hello')
if __name__ == '__main__':
mp.set_start_method('spawn')
q = mp.Queue()
p = mp.Process(target=foo, args=(q,))
p.start()
print(q.get())
p.join()