lua垃圾收集从C推来的火炬张量吗?
Does lua garbage collect torch tensors pushed from C?
根据这个答案(https://groups.google.com/forum/#!msg/torch7/rmIcBYCiFG8/IC68Xzd3DgAJ),似乎火炬会自动释放不再使用的张量。我已经遇到了这个问题,张量指针被lua自动释放,导致c程序出现段错误。然而,从我的实验来看,似乎没有在C代码上手动调用free会导致内存泄漏,其中程序内存不断增加。
下面是我的测试代码:#include <iostream>
#include <chrono>
#include <thread>
#include <lua.hpp>
extern "C" {
#include <TH.h>
#include <luaT.h>
}
using namespace std;
int main(int argc, char** argv)
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "require");
lua_pushstring(L, "torch");
lua_pcall(L,1,0,0); // require "torch"
int h=224, w=224, nb_channel=3;
int len = h * w * nb_channel;
long stride_1 = h * w;
long stride_2 = w;
long stride_3 = 1;
for (size_t i = 0 ; i < 1000000 ; ++i)
{
float *tensorData = (float*)malloc(sizeof(float)*len); // Should be when the storage is freed
THFloatStorage *storage = THFloatStorage_newWithData(tensorData, len); // Memory released when tensor input is freed by lua garbadge collector
THFloatTensor* input = THFloatTensor_newWithStorage3d(storage,
0, // Offset
nb_channel, stride_1, // Channels
h, stride_2, // Height
w, stride_3); // Width
// Do some initialisation of the tensor...
luaT_pushudata(L, (void*) input, "torch.FloatTensor"); // Send the tensor to lua
// Do some stuff with the input... (call lua torch scripts...)
lua_pop(L, 1);
// If those two lines is not set, we get a memory leak
THFloatTensor_free(input); // Will sometimes create a segfault as the tensor seems to be deleted by the lua garbadge collector
THFloatStorage_free(storage);
if (i%10000 == 0)
std::cout << i << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
return 0;
}
如何使用c和lua正确管理内存以避免段错误而不产生内存泄漏
我认为您正在获得内存泄漏,因为在这一行中没有为"tensordata"释放内存floattensorData = (float)malloc(sizeof(float)*len);
希望有所帮助
相关文章:
- 使用Pybind11向Python公开Eigen::张量
- C++中的张量流对象检测
- 在官方张量流 resnet50 模型上运行 tflite 精度工具
- PyTorch C++将数据转换为张量失败
- 如何使用 c++ 更改张量流中的per_process_gpu_memory_fraction?
- 编译 GPU 的张量流示例自定义操作
- 在 Torch C++ API 中,如何快速写入张量的内部数据?
- 如何在C++中将一个特征张量乘以另一个特征张量的标量和?
- C++ ABI 兼容性问题/张量流
- 如何从内存缓冲区加载张量流图
- PyTorch C++ 前端向前返回多个张量
- 从 std::向量值创建张量<Tensor>
- 张量流错误 此文件需要编译器和库支持 ISO C++ 2011 标准
- 如何将自定义特征张量类存储到 std::vector 中?
- CUDA 高效的 nd-array(张量)切片
- 部署在张量流中训练的神经网络来火炬C++的最佳方法是什么?
- 张量(多维数组)是树前瞻数据的有效存储类型吗?
- 我们可以在Mac上有多个张量流式版本吗?
- 在C++中,这个Eigen::张量的声明是安全的,还是有缺陷的?我应该为它提交一个问题吗
- lua垃圾收集从C推来的火炬张量吗?