如何阅读TensorFlow源码

通过bazel学习之后,大概了解了TensorFlow的项目的源文件和描述文件。

下面是一篇不错的介绍,搬砖here

在静下心来默默看了大半年机器学习的资料并做了些实践后,打算学习下现在热门的TensorFlow的实现,毕竟系统这块和自己关系较大。本文会简单的说明一下如何阅读TensorFlow的源码。最重要的是了解其构建工具bazel以及脚本语言调用c或cpp的包裹工具swig。这里假设大家对bazel及swig以及有所了解(不了解的可以google下)。要看代码首先要知道代码怎么构建,因此本文的一大部分会关注构建这块。

如果从源码构建TensorFlow会需要执行如下命令:

bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
 
 
对应的BUILD文件的rule为:

 
 
  1. sh_binary(
  2. name = "build_pip_package",
  3. srcs = [ "build_pip_package.sh"],
  4. data = [
  5. "MANIFEST.in",
  6. "README",
  7. "setup.py",
  8. "//tensorflow/core:framework_headers",
  9. ":other_headers",
  10. ":simple_console",
  11. "//tensorflow:tensorflow_py",
  12. "//tensorflow/examples/tutorials/mnist:package",
  13. "//tensorflow/models/embedding:package",
  14. "//tensorflow/models/image/cifar10:all_files",
  15. "//tensorflow/models/image/mnist:convolutional",
  16. "//tensorflow/models/rnn:package",
  17. "//tensorflow/models/rnn/ptb:package",
  18. "//tensorflow/models/rnn/translate:package",
  19. "//tensorflow/tensorboard",
  20. ],
  21. )

sh_binary在这里的主要作用是生成data的这些依赖。一个一个来看,一开始的三个文件MANIFEST.in、README、setup.py是直接存在的,因此不会有什么操作。
“//tensorflow/core:framework_headers”:
其对应的rule为:


 
 
  1. filegroup(
  2. name = "framework_headers",
  3. srcs = [
  4. "framework/allocator.h",
  5. ......
  6. "util/device_name_utils.h",
  7. ],
  8. )

这里filegroup的作用是给这一堆头文件一个别名,方便其他rule引用。
“:other_headers”:
rule为:


 
 
  1. transitive_hdrs(
  2. name = "other_headers",
  3. deps = [
  4. "//third_party/eigen3",
  5. "//tensorflow/core:protos_all_cc",
  6. ],
  7. )

transitive_hdrs的定义在:

load("//tensorflow:tensorflow.bzl", "transitive_hdrs")
 
 
实现为:

 
 
  1. # Bazel rule for collecting the header files that a target depends on.
  2. def _transitive_hdrs_impl(ctx):
  3. outputs = set()
  4. for dep in ctx.attr.deps:
  5. outputs += dep.cc.transitive_headers
  6. return struct(files=outputs)
  7. _transitive_hdrs = rule(attrs={
  8. "deps": attr.label_list(allow_files= True,
  9. providers=[ "cc"]),
  10. },
  11. implementation=_transitive_hdrs_impl,)
  12. def transitive_hdrs(name, deps=[], **kwargs):
  13. _transitive_hdrs(name=name + "_gather",
  14. deps=deps)
  15. native.filegroup(name=name,
  16. srcs=[ ":" + name + "_gather"])

其作用依旧是收集依赖需要的头文件。

“:simple_console”:
其rule为:


 
 
  1. py_binary(
  2. name = "simple_console",
  3. srcs = [ "simple_console.py"],
  4. srcs_version = "PY2AND3",
  5. deps = [ "//tensorflow:tensorflow_py"],
  6. )

 
 
  1. py_library(
  2. name = "tensorflow_py",
  3. srcs = [ "__init__.py"],
  4. srcs_version = "PY2AND3",
  5. visibility = [ "//visibility:public"],
  6. deps = [ "//tensorflow/python"],
  7. )
simple_console.py的代码的主要部分是:

 
 
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import code
  5. import sys
  6. def main(_):
  7. """Run an interactive console."""
  8. code.interact()
  9. return 0
  10. if __name__ == '__main__':
  11. sys.exit(main(sys.argv))
可以看到起通过deps = [“//tensorflow/python”]构建了依赖包,然后生成了对应的执行文件。看下依赖的rule规则。
//tensorflow/python对应的rule为:


 
 
  1. py_library(
  2. name = "python",
  3. srcs = [
  4. "__init__.py",
  5. ],
  6. srcs_version = "PY2AND3",
  7. visibility = [ "//tensorflow:__pkg__"],
  8. deps = [
  9. ":client",
  10. ":client_testlib",
  11. ":framework",
  12. ":framework_test_lib",
  13. ":kernel_tests/gradient_checker",
  14. ":platform",
  15. ":platform_test",
  16. ":summary",
  17. ":training",
  18. "//tensorflow/contrib:contrib_py",
  19. ],
  20. )
这里如果仔细看的话会发现其主要是生成一堆python的模块。从这里貌似可以看出每个python的module都对应了一个rule,且module依赖的module都写在了deps里。特别的,作为一个C++的切入,我们关注下training这个依赖:

 
 
  1. py_library(
  2. name = "training",
  3. srcs = glob(
  4. [ "training/**/*.py"],
  5. exclude = [ "**/*test*"],
  6. ),
  7. srcs_version = "PY2AND3",
  8. deps = [
  9. ":client",
  10. ":framework",
  11. ":lib",
  12. ":ops",
  13. ":protos_all_py",
  14. ":pywrap_tensorflow",
  15. ":training_ops",
  16. ],
  17. )
这里其依赖的pywrap_tensorflow的rule为:


 
 
  1. tf_py_wrap_cc(
  2. name = "pywrap_tensorflow",
  3. srcs = [ "tensorflow.i"],
  4. swig_includes = [
  5. "client/device_lib.i",
  6. "client/events_writer.i",
  7. "client/server_lib.i",
  8. "client/tf_session.i",
  9. "framework/python_op_gen.i",
  10. "lib/core/py_func.i",
  11. "lib/core/status.i",
  12. "lib/core/status_helper.i",
  13. "lib/core/strings.i",
  14. "lib/io/py_record_reader.i",
  15. "lib/io/py_record_writer.i",
  16. "platform/base.i",
  17. "platform/numpy.i",
  18. "util/port.i",
  19. "util/py_checkpoint_reader.i",
  20. ],
  21. deps = [
  22. ":py_func_lib",
  23. ":py_record_reader_lib",
  24. ":py_record_writer_lib",
  25. ":python_op_gen",
  26. ":tf_session_helper",
  27. "//tensorflow/core/distributed_runtime:server_lib",
  28. "//tensorflow/core/distributed_runtime/rpc:grpc_server_lib",
  29. "//tensorflow/core/distributed_runtime/rpc:grpc_session",
  30. "//util/python:python_headers",
  31. ],
  32. )
tf_py_wrap_cc为其自己实现的一个rule,这里的.i就是SWIG的interface文件。来看下其实现:

 
 
  1. def tf_py_wrap_cc(name, srcs, swig_includes=[], deps=[], copts=[], **kwargs):
  2. module_name = name.split( "/")[ -1]
  3. # Convert a rule name such as foo/bar/baz to foo/bar/_baz.so
  4. # and use that as the name for the rule producing the .so file.
  5. cc_library_name = "/".join(name.split( "/")[: -1] + [ "_" + module_name + ".so"])
  6. extra_deps = []
  7. _py_wrap_cc(name=name + "_py_wrap",
  8. srcs=srcs,
  9. swig_includes=swig_includes,
  10. deps=deps + extra_deps,
  11. module_name=module_name,
  12. py_module_name=name)
  13. native.cc_binary(
  14. name=cc_library_name,
  15. srcs=[module_name + ".cc"],
  16. copts=(copts + [ "-Wno-self-assign", "-Wno-write-strings"]
  17. + tf_extension_copts()),
  18. linkopts=tf_extension_linkopts(),
  19. linkstatic= 1,
  20. linkshared= 1,
  21. deps=deps + extra_deps)
  22. native.py_library(name=name,
  23. srcs=[ ":" + name + ".py"],
  24. srcs_version= "PY2AND3",
  25. data=[ ":" + cc_library_name])
按照SWIG的正常流程,先要通过swig命令生成我们的wrap的c文件,然后和依赖生成我们的so文件,最后生成一个同名的python文件用于import。这里native.cc_binary和native.py_library做了我们后面的两件事情,而swig命令的执行则交给了_py_wrap_cc。其实现为:


 
 
  1. _py_wrap_cc = rule(attrs={
  2. "srcs": attr.label_list(mandatory= True,
  3. allow_files= True,),
  4. "swig_includes": attr.label_list(cfg=DATA_CFG,
  5. allow_files= True,),
  6. "deps": attr.label_list(allow_files= True,
  7. providers=[ "cc"],),
  8. "swig_deps": attr.label(default=Label(
  9. "//tensorflow:swig")), # swig_templates
  10. "module_name": attr.string(mandatory= True),
  11. "py_module_name": attr.string(mandatory= True),
  12. "swig_binary": attr.label(default=Label( "//tensorflow:swig"),
  13. cfg=HOST_CFG,
  14. executable= True,
  15. allow_files= True,),
  16. },
  17. outputs={
  18. "cc_out": "%{module_name}.cc",
  19. "py_out": "%{py_module_name}.py",
  20. },
  21. implementation=_py_wrap_cc_impl,)
_py_wrap_cc_impl的实现为:


 
 
  1. # Bazel rules for building swig files.
  2. def _py_wrap_cc_impl(ctx):
  3. srcs = ctx.files.srcs
  4. if len(srcs) != 1:
  5. fail( "Exactly one SWIG source file label must be specified.", "srcs")
  6. module_name = ctx.attr.module_name
  7. cc_out = ctx.outputs.cc_out
  8. py_out = ctx.outputs.py_out
  9. src = ctx.files.srcs[ 0]
  10. args = [ "-c++", "-python"]
  11. args += [ "-module", module_name]
  12. args += [ "-l" + f.path for f in ctx.files.swig_includes]
  13. cc_include_dirs = set()
  14. cc_includes = set()
  15. for dep in ctx.attr.deps:
  16. cc_include_dirs += [h.dirname for h in dep.cc.transitive_headers]
  17. cc_includes += dep.cc.transitive_headers
  18. args += [ "-I" + x for x in cc_include_dirs]
  19. args += [ "-I" + ctx.label.workspace_root]
  20. args += [ "-o", cc_out.path]
  21. args += [ "-outdir", py_out.dirname]
  22. args += [src.path]
  23. outputs = [cc_out, py_out]
  24. ctx.action(executable=ctx.executable.swig_binary,
  25. arguments=args,
  26. mnemonic= "PythonSwig",
  27. inputs=sorted(set([src]) + cc_includes + ctx.files.swig_includes +
  28. ctx.attr.swig_deps.files),
  29. outputs=outputs,
  30. progress_message= "SWIGing {input}".format(input=src.path))
  31. return struct(files=set(outputs))
这里的ctx.executable.swig_binary是一个shell脚本,内容为:


 
 
  1. # If possible, read swig path out of "swig_path" generated by configure
  2. SWIG=swig
  3. SWIG_PATH=tensorflow/tools/swig/swig_path
  4. if [ -e $SWIG_PATH ]; then
  5. SWIG=`cat $SWIG_PATH`
  6. fi
  7. # If this line fails, rerun configure to set the path to swig correctly
  8. "$SWIG" "$@"

可以看到起就是调用了swig命令。

“//tensorflow:tensorflow_py”:
其rule为:


 
 
  1. py_library(
  2. name = "tensorflow_py",
  3. srcs = [ "__init__.py"],
  4. srcs_version = "PY2AND3",
  5. visibility = [ "//visibility:public"],
  6. deps = [ "//tensorflow/python"],
  7. )

可以看到起主要依赖了我们上面生成的”//tensorflow/python”这个module。

剩余的几个其实和主框架关系不大,主要是生成一些model、文档啥的。

现在清楚了其构建链后,我们来看个简单的程序,其通过梯度下降算法求线性拟合的W和b。我们会从这个例子入手看下如何找到其使用的函数的具体实现的源码位置:


 
 
  1. (python3 .5)➜ tmp cat th.py
  2. import tensorflow as tf
  3. import numpy as np
  4. x_data = np.random.rand( 100).astype(np.float32)
  5. y_data = x_data * 0.1 + 0.3
  6. W = tf.Variable(tf.random_uniform([ 1], -1.0, 1.0))
  7. b = tf.Variable(tf.zeros([ 1]))
  8. y = W * x_data + b
  9. loss = tf.reduce_mean(tf.square(y - y_data))
  10. optimizer = tf.train.GradientDescentOptimizer( 0.5)
  11. train = optimizer.minimize(loss)
  12. init = tf.initialize_all_variables()
  13. sess = tf.Session()
  14. sess.run(init)
  15. for step in range( 0, 201):
  16. sess.run(train)
  17. if step % 20 == 0:
  18. print(step, sess.run(W), sess.run(b))
  19. (python3 .5)➜ tmp python th.py
  20. 0 [ 0.42190057] [ 0.17155224]
  21. 20 [ 0.1743494] [ 0.26045772]
  22. 40 [ 0.11817314] [ 0.29033473]
  23. 60 [ 0.10444205] [ 0.29763755]
  24. 80 [ 0.10108578] [ 0.29942256]
  25. 100 [ 0.10026541] [ 0.29985884]
  26. 120 [ 0.10006487] [ 0.2999655]
  27. 140 [ 0.10001585] [ 0.29999158]
  28. 160 [ 0.10000388] [ 0.29999796]
  29. 180 [ 0.10000096] [ 0.29999951]
  30. 200 [ 0.10000025] [ 0.29999989]
从我们上面的分析可以看到,import tensorflow as tf来自于tensorflow目录下的__init__.py文件,其内容为:

from tensorflow.python import *
 
 
再来看tf.Variable,在tensorflow.python的__init__.py中可以看到其导入了很多符号。但要定位到Variable还是比较困难,因为其很多直接是import *。所以一个快速定位的方法是直接grep这个class:


 
 
  1. ➜ python grep 'class Variable(' -R ./*
  2. ./ops/variables.py: class Variable(object):

对于tf.Session等也可以用同样的方法定位。我们来找个走SWIG包裹的,如果我们去看sess.run,我们会看到如下的代码:


 
 
  1. return tf_session.TF_Run(session, options,
  2. feed_dict, fetch_list, target_list,
  3. run_metadata)
这里tf_session就是一个SWIG包裹的模块:
from tensorflow.python import pywrap_tensorflow as tf_session
 
 
pywrap_tensorflow在源码里是找不到的,因为这个得从SWIG生成后才有,我们可以从.i文件里找下TF_Run的声明,或者直接grep下这个函数:

 
 
  1. ➜ tensorflow grep 'TF_Run(' -R ./*
  2. ./core/client/tensor_c_api.cc:void TF_Run(TF_Session* s, const TF_Buffer* run_options,
这样就可以看其实现了:

 
 
  1. void TF_Run(TF_Session* s, const TF_Buffer* run_options,
  2. // Input tensors
  3. const char** c_input_names, TF_Tensor** c_inputs, int ninputs,
  4. // Output tensors
  5. const char** c_output_tensor_names, TF_Tensor** c_outputs,
  6. int noutputs,
  7. // Target nodes
  8. const char** c_target_node_names, int ntargets,
  9. TF_Buffer* run_metadata, TF_Status* status) {
  10. TF_Run_Helper(s, nullptr, run_options, c_input_names, c_inputs, ninputs,
  11. c_output_tensor_names, c_outputs, noutputs, c_target_node_names,
  12. ntargets, run_metadata, status);
  13. }


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值