c++ - 在 C++ 中运行 TensorFlow 时的显着 RAM 成本
问题描述
我目前正在使用带有 C++ API 的 GPU 机器上经过训练的 TensorFlow 图编写一些推理代码。
这是我的设置:
- 平台:CentOS 7
- TensorFlow 版本:TensorFlow 1.5
- CUDA 版本:CUDA 9.0
- C++ 版本:C++11
我正在努力解决几个问题。
1) 首先,我按照本教程学习了在 C++ 中加载图形的基本模板。本教程中的示例非常简单,但是当我运行该程序时(在 GPU 机器上),它占用了将近0.9G的 RAM。
2)我的图表比那个教程中的图表要复杂得多。大约有 20 层,层中的节点数从 300 到 5000 不等。
我的(伪)代码片段在这里。为简单起见,我只保留导致(潜在)内存问题的代码:
tensorflow::Tensor input = getDataFromSomewhere(...);
int length = size of the input;
int g_batch_size = 50;
// 1) Create session...
// 2) Load graph...
// 3) Inference
for (int x = 0; x < length; x += g_batch_size) {
tensorflow::Tensor out;
auto cur_slice = input.Slice(x, std::min(x + g_batch_size, length));
inference(cur_slice, out);
// doSomethingWithOutput(out);
}
// 4) Close session and free session memory
// Inference helper function
tensorflow::Status inference(tensorflow::Tensor& input_tensors, tensorflow::Tensor& out) {
// This line increases a lot more memory usage
TensorDict feed_dict = {{"IteratorGetNext:0", input_tensors}};
std::vector<tensorflow::Tensor> outputs;
tensorflow::Status status = session->Run(feed_dict, {"final_dense:0"}, {}, &outputs);
// UpdateOutWithOutputs();
return tensorflow::Status::OK();
}
创建会话并加载图表后,内存成本约为1.2G。
然后,正如我在代码中指出的那样,当程序达到 时session->Run(...)
,内存使用量上升到超过2G。
我不确定这是否是 TensorFlow 的正常行为。我已经检查了这个和这个线程,但我不太清楚我是否在我的代码中创建了冗余操作。
任何意见或建议表示赞赏!提前致谢!
解决方案
我发现的问题是Tensorflow
动态库大约需要200MB,而CUDA
动态库需要超过500MB内存。所以加载这些库已经占用了大量的内存。
推荐阅读
- ruby-on-rails - 渲染 rails form_tag 部分时出错
- ruby-on-rails - 有时我会因为时间的原因得到失败的香料。现在,不明白为什么
- excel - 通过VBA为所有工作表中的指定单元格设置一个值
- java - 为什么jdbc调用存储过程“插入本地表,选择本地表”CallableStatement.execute返回false?
- flutter - 如何在构建方法之外访问 mediaquery.of(context).width.height?
- html - 没有引导程序就无法换行的图像和文本?
- java - 在非活动类中获取原始资源(声音)
- javascript - 使用 regEx 验证属性名称
- c# - 如何验证xml属性是否存在于c#中
- powerbi - Power BI - 除法返回 1