高性能程序设计
TensorFlow内核采用C/C++开发,并提供了C++,Python,Java,Go语言的Client API。特别是Python API,是目前主流的TensorFlow模型开发接口。但为什么还需要采用C++ API去训练模型呢?本文基于如下两点考虑,首先当我们采用Python API去训练模型的时候,需要不断地用Python API调用C/C++底层接口,重复的接口调用一定程度上影响了程序的执行性能。更为重要的是,在GPU上训练模型的时候需要大量的内存交换;如果采用C++ API去训练模型,可提供更好的运算性能及更好地控制GPU内存的分配。
下图为Python API的运算架构:在模型训练的每次迭代中,程序通过Python API读取Batch Data,然后通过TensorFlow Session Run接口,传递数据给C++,并触发神经网络训练。如下图所示:

下图为C++ API的运算架构:在模型训练的每次迭代中,通过C++ API读取Batch Data后,直接触发模型训练。减少了不同语言间API接口的循环调用及数据传输。如下图所示:

为了采用C++ API进行模型训练,我们首先需要编写训练模型,这个编写过程可以采用Python语言来完成。我们首先采用Python API编写训练模型,然后把图模型转换为Protobuf的序列化文件。接着通过C++ API加载该模型文件,创建TensorFlow Session,初始化模型变量,以及加载训练数据并执行神经网络训练。程序架构如下图所示:

下面为使用Python API定义训练模型的示例:
with tf.Session() as sess:
#定义Placeholder Tensor接入训练数据
x = tf.placeholder(tf.float32, [None, 32], name="x")
y = tf.placeholder(tf.float32, [None, 8], name="y")
#定义训练模型
w1 = tf.Variable(tf.truncated_normal([32, 16], stddev=0.1))
b1 = tf.Variable(tf.constant(0.0, shape=[16]))
w2 = tf.Variable(tf.truncated_normal([16, 8], stddev=0.1))
b2 = tf.Variable(tf.constant(0.0, shape=[8]))
a = tf.nn.tanh(tf.nn.bias_add(tf.matmul(x, w1), b1))
y_out = tf.nn.tanh(tf.nn.bias_add(tf.matmul(a, w2), b2), name="y_out")
cost = tf.reduce_sum(tf.square(y-y_out), name="cost")
optimizer = tf.train.AdamOptimizer().minimize(cost, name="train")
#定义变量初始化操作
init = tf.initialize_variables(tf.all_variables(), name='init_all_vars_op')
#把图模型转换为Protobuf文件
tf.train.write_graph(sess.graph_def, './', 'mlp.pb', as_text=False)
下面为使用C++ API加载Protobuf图模型,并执行训练的示例:
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/graph/default_device.h"
using namespace tensorflow;
int main(int argc, char* argv[]) {
//Protobuf模型文件名
std::string graph_definition = "mlp.pb";
//Tensorflow Sesssion
Session* session;
//定义图模型对象
GraphDef graph_def;
SessionOptions opts;
//存储Session会话的运行结果
std::vector<Tensor> outputs;
#加载Protobuf模型文件到图模型对象中
TF_CHECK_OK(ReadBinaryProto(Env::Default(), graph_definition, &graph_def));
// 默认在gpu 0上执行模型的训练操作
graph::SetDefaultDevice("/gpu:0", &graph_def);
//设定GPU显存使用参数
opts.config.mutable_gpu_options()->set_per_process_gpu_memory_fraction(0.5);
opts.config.mutable_gpu_options()->set_allow_growth(true);
//创建TensorFlow会话
TF_CHECK_OK(NewSession(opts, &session));
// 加载图对象到会话中
TF_CHECK_OK(session->Create(graph_def));
// 执行模型参数初始化操作
TF_CHECK_OK(session->Run({}, {}, {"init_all_vars_op"}, nullptr));
//定义模型输入数据,包括数据类型和维度信息
Tensor x(DT_FLOAT, TensorShape({100, 32}));
Tensor y(DT_FLOAT, TensorShape({100, 8}));
//把Tensor转换为矩阵,并初始化Tensor数据
auto _XTensor = x.matrix<float>();
auto _YTensor = y.matrix<float>();
_XTensor.setRandom();
_YTensor.setRandom();
for (int i = 0; i < 10; ++i) {
//执行模型的训练操作,{{"x", x}, {"y", y}}表示输入数据Tensor名称和Tensor对象;{"cost"}表示要获取输出值的操作名称;&outputs表示执行"cost"操作后返回的Tensor对象
TF_CHECK_OK(session->Run({{"x", x}, {"y", y}}, {"cost"}, {}, &outputs));
//获取执行“cost“操作后的运算结果
float cost = outputs[0].scalar<float>()(0);
std::cout << "Cost: " << cost << std::endl;
//执行"train"操作
TF_CHECK_OK(session->Run({{"x", x}, {"y", y}}, {}, {"train"}, nullptr)); // Train
outputs.clear();
}
//关闭Session及删除Session对象
session->Close();
delete session;
return 0;
}
当C++程序写好后,编译时候需要链接的头文件,开源已经帮我们整理好了,存放于目录/usr/lib/python2.7/site-packages/tensorflow/include下。编译和运行的时候需要链接libtensorflow_cc.so,可以按照下面的方式编译该库文件:bazel build -c opt //tensorflow:libtensorflow_cc.so --copt=-m64 --linkopt=-m64 --spawn_strategy=standalone --genrule_strategy=standalone --verbose_failures。具体可参考TensorFlow源代码的官方编译文档。
总结
本文首先回顾了TensorFlow 1.0主要新特性及TensorFlow 2017 Dev Summit的主要议程。到目前为止TensorFlow的GitHub Star排名为51000+, Fork排名已达24000+,有15000+ commits。并随着TensorFlow新版本的不断发布以及新特性的不断增加,TensorFlow使用更加灵活,运行速度更快,使用方式更产品化,已成为目前主流的深度学习平台之一。
接着介绍了TensorFlow的系统架构,包括Client,Master,Worker,Kernel的相关概念及运行方式,是一种适合大规模分布式训练的机器学习平台。从上述系统架构中可以看到,TensorFlow内核采用C/C++开发,当采用Python API去训练模型的时候,需要不断地用Python调用C/C++底层接口,重复的接口调用一定程度上影响了程序的执行性能。如果有最求高性能运算的朋友,可以尝试用下本文高性能运算章节推荐的方法。
参考文献
- http://www.tensorflow.org
- 深度学习利器:分布式TensorFlow及实例分析
- 深度学习利器:TensorFlow使用实战
作者介绍
武维(邮箱:3381209@qq.com),博士,现为IBM Spectrum Computing 研发工程师。主要从事大数据,深度学习,云计算等领域的研发工作。
本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-04/143079.htm
