【一】代码下载git
https://github.com/tensorflow/tensorflow/releases/github
PS:本次源码分析采用1.11版本设计模式
【二】Session简介api
在TensorFlow中,session是沟通tf的桥梁,模型的训练、推理,都须要经过session,session持有graph的引用。tf支持单机与分布式,所以session也分为单机版与分布式版。session
【三】session类图分布式
Session ::tensorflow\core\public\session.hide
DirectSession ::tensorflow\core\common_runtime\direct_session.h源码分析
GrpcSession ::tensorflow\core\distributed_runtime\rpc\grpc_session.h设计
class DirectSession : public Session --->单机版sessionorm
class GrpcSession : public Session ---> 分布式版session
【四】session建立
tf对外提供了一套C API,负责给client语言使用。在tensorflow\c\c_api.h中,session的建立流程咱们从这里开始。
TF_NewSession
NewSession (tensorflow\core\public\session.h)
1. NewSession实现 tensorflow\core\common_runtime\session.cc
Status NewSession(const SessionOptions& options, Session** out_session) {
SessionFactory* factory;
Status s = SessionFactory::GetFactory(options, &factory); // 经过SessionOptions来选择不一样的factory
s = factory->NewSession(options, out_session); // 调用对应的factory来建立对应的session,也就是建立DirectSession 还GrpcSession
}
2. 关于SessionOptions
这里看一下该定义,省略掉其余成员,仅仅看看target,注释中说,若是target为空,则建立DirectSession,若是target以 'grpc’开头,则建立GrpcSession
/// Configuration information for a Session.
struct SessionOptions {
/// \brief The TensorFlow runtime to connect to.
///
/// If 'target' is empty or unspecified, the local TensorFlow runtime
/// implementation will be used. Otherwise, the TensorFlow engine
/// defined by 'target' will be used to perform all computations.
///
/// "target" can be either a single entry or a comma separated list
/// of entries. Each entry is a resolvable address of the
/// following format:
/// local
/// ip:port
/// host:port
/// ... other system-specific formats to identify tasks and jobs ...
///
/// NOTE: at the moment 'local' maps to an in-process service-based
/// runtime.
///
/// Upon creation, a single session affines itself to one of the
/// remote processes, with possible load balancing choices when the
/// "target" resolves to a list of possible processes.
///
/// If the session disconnects from the remote process during its
/// lifetime, session calls may fail immediately.
string target;
};
3. SessionFactory::GetFactory
这里的关键在于:session_factory.second->AcceptsOptions(options)
依据选项来,这里其实是调用对应的factory方法
DirectSessionFactory
bool AcceptsOptions(const SessionOptions& options) override {
return options.target.empty(); // target为空则为true
}
GrpcSessionFactory
bool AcceptsOptions(const SessionOptions& options) override {
return str_util::StartsWith(options.target, kSchemePrefix); // const char* const kSchemePrefix = "grpc://"; target为grpc开头
}
class GrpcSessionFactory : public SessionFactory
class DirectSessionFactory : public SessionFactory
【五】总结
session的建立经过option(能够理解为配置)来选择性建立,而session的真正建立由sessionfactory来完成,这里采用了工厂设计模式,将各个factory经过注册的方式注册到sessionfactory中,这样在系统启动后,这些factory就能够用了,新增一个factory也很容易,且不影响上层代码。