首页 > 解决方案 > 运行 mxnet cpu 推理时内存泄漏

问题描述

我测试了 100 张图片,下面列出了 memory_profiler 的分析。为什么第 308 行会导致大量内存增长?

mxnet==1.5.1

Line #    Mem usage    Increment   Line Contents
================================================
   297 8693.719 MiB   81.809 MiB           data = nd.array(im_tensor)
   298 8693.719 MiB    0.000 MiB           db = mx.io.DataBatch(data=(data,), provide_data=[('data', data.shape)])
   299 8630.039 MiB    2.840 MiB           self.model.forward(db, is_train=False)
   300 8630.039 MiB    2.320 MiB           net_out = self.model.get_outputs()
   301 8693.719 MiB    2.062 MiB           for _idx,s in enumerate(self._feat_stride_fpn):
   302 8693.719 MiB    2.062 MiB               _key = 'stride%s'%s
   303 8693.719 MiB    1.031 MiB               stride = int(s)
   304 8693.719 MiB    1.031 MiB               if self.use_landmarks:
   305 8693.719 MiB    1.031 MiB                 idx = _idx*3
   306                                         else:
   307                                           idx = _idx*2
   308 8693.719 MiB 4700.676 MiB               scores = net_out[idx].asnumpy()
   309 8693.719 MiB    1.289 MiB               print scores.shape
   310 8693.719 MiB    1.031 MiB               scores = scores[:, self._num_anchors['stride%s'%s]:, :, :]
   311 8693.719 MiB    1.031 MiB               idx+=1
   312 8693.719 MiB    2.836 MiB               bbox_deltas = net_out[idx].asnumpy()
   ...

标签: pythonmxnet

解决方案


MXNet python API 调用实际上只是在 MXNet 后端引擎中排队,并在 C++ 中异步处理。因此,您在此 python 分析器中看到的内容可能无法反映幕后实际发生的情况。对于分析,我建议您查看专用工具:https ://mxnet.apache.org/api/python/docs/tutorials/performance/backend/profiler.html

我怀疑您的.asnumpy()调用与高内存使用有关,因为它是一个阻塞调用:它需要立即获得结果,因此迫使 mxnet 引擎立即计算必要的依赖关系。一般建议在 MXNet 代码中避免使用 NumpyMXNet NDArray改用,它比 Numpy 更适合深度学习(异步、GPU 兼容、支持自动微分)。例如,您可以在 an 中积累您需要的任何信息MXNet NDArray,然后在执行结束时使用它做任何您需要的事情(保存到文件、转换为 Numpy 等)。更多资源:


推荐阅读