python - 运行 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()
...
解决方案
MXNet python API 调用实际上只是在 MXNet 后端引擎中排队,并在 C++ 中异步处理。因此,您在此 python 分析器中看到的内容可能无法反映幕后实际发生的情况。对于分析,我建议您查看专用工具:https ://mxnet.apache.org/api/python/docs/tutorials/performance/backend/profiler.html
我怀疑您的.asnumpy()
调用与高内存使用有关,因为它是一个阻塞调用:它需要立即获得结果,因此迫使 mxnet 引擎立即计算必要的依赖关系。一般建议在 MXNet 代码中避免使用 Numpy并MXNet NDArray
改用,它比 Numpy 更适合深度学习(异步、GPU 兼容、支持自动微分)。例如,您可以在 an 中积累您需要的任何信息MXNet NDArray
,然后在执行结束时使用它做任何您需要的事情(保存到文件、转换为 Numpy 等)。更多资源:
- MXNet 中有关 Numpy 与 NDArray 的常见提示
- 这个答案提供了与 Numpy 和 MXNet NDArray 的差异摘要
推荐阅读
- windows - PowerShell to get all the processes which are using(i.g. write/read to the file, etc) a given file name
- c# - C#将输入中的2个数据网格视图列相乘并将结果放在第三列中
- python - 解析并创建一个带有条件的新df
- javascript - Why accessible-autocomplete with preact ignores displayMenu='overlay' option
- python - 张量流中的可变形卷积
- java - Mysql RELEASE_LOCK is not releasing lock
- dart - Dart beginning - unable to run AngularDart Web App template
- jmeter - 如何将 .csv 文件中的数据用于 Ultimate 线程组
- reactjs - Uploading images through firebase functions
- angular - 生产时,角度动态组件创建不起作用