我使用FastAI(PyTorch后端)在GPU上训练了一个CNN模型。现在,我正在尝试在同一台机器上使用CPU而不是GPU对该模型进行推断。同时,我还尝试使用多个CPU核心,使用multiprocessing模块。现在遇到的问题是:
在单个CPU上运行代码(未使用multiprocessing)只需40秒即可处理近50张图像
使用torch multiprocessing在多个CPU上运行代码需要超过6分钟才能处理相同的50张图像
from torch.multiprocessing import Pool, set_start_method
os.environ['CUDA_VISIBLE_DEVICES']=""
from fastai.vision import *
from fastai.text import *
defaults.device = torch.device('cpu')
def process_image_batch(batch):
learn_cnn = load_learner(scripts_folder, 'cnn_model.pkl')
learn_cnn.model.training = False
learn_cnn.model = learn_cnn.model.eval()
# for image in batch:
# prediction = ... # predicting the image here
# return prediction
if __name__ == '__main__':
#
# image_batches = ..... # retrieving the image batches (It is a list of 5 lists)
# n_processes = 5
set_start_method('spawn', force=True)
try:
pool = Pool(n_processes)
pool.map(process_image_batch, image_batches)
except Exception as e:
print('Main Pool Error: ', e)
except KeyboardInterrupt:
exit()
finally:
pool.terminate()
pool.join()
我不确定是什么原因导致多进程模式变慢。我已经阅读了很多帖子讨论类似的问题,但无法在任何地方找到合适的解决方案。
torch.set_num_threads(1)
- asanoop24