【发布时间】:2019-09-12 16:55:33
【问题描述】:
我有以下 Pytorch 代码,代码的作用是:
- 使用
net=CRAFT()将 Pytorch 对象检测模型加载到 RAM 中 - 使用
net.eval()运行推理 - 我使用 for 循环提供图像以逐一运行推理
代码:
def copyStateDict(state_dict):
if list(state_dict.keys())[0].startswith("module"):
start_idx = 1
else:
start_idx = 0
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = ".".join(k.split(".")[start_idx:])
new_state_dict[name] = v
return new_state_dict
if __name__ == '__main__':
# load net
net = CRAFT() # initialize
print('Loading weights from checkpoint (' + args.trained_model + ')')
if args.cuda:
net.load_state_dict(copyStateDict(torch.load(args.trained_model)))
else:
net.load_state_dict(copyStateDict(torch.load(args.trained_model, map_location='cpu')))
if args.cuda:
net = net.cuda()
net = torch.nn.DataParallel(net)
cudnn.benchmark = False
net.eval()
t = time.time()
# load data
for k, image_path in enumerate(image_list):
print("Test image {:d}/{:d}: {:s}".format(k+1, len(image_list), image_path), end='\r')
image = imgproc.loadImage(image_path)
bboxes, polys, score_text = test_net(net, image, args.text_threshold, args.link_threshold, args.low_text, args.cuda, args.poly)
# save score text
#filename, file_ext = os.path.splitext(os.path.basename(image_path))
#mask_file = result_folder + "/res_" + filename + '_mask.jpg'
#cv2.imwrite(mask_file, score_text)
file_utils.saveResult(image_path, image[:,:,::-1], polys, dirname=result_folder)
print("elapsed time : {}s".format(time.time() - t))
这段代码有一个警告,尤其是我每次执行步骤 1 和 2 时它都会占用1.8 GB 的 RAM。对图像的实际推断需要更少的 RAM(每张图像 40mb),但我的大部分内存消耗来自将 ML 模型加载到 RAM 中。有没有一种方法可以让我将此模型继续加载到服务器上的 RAM 中,然后仅对图像执行推断?
【问题讨论】: