【一】代码下载
https://github.com/tensorflow/tensorflow/releases/
PS:本次源码分析采用1.11版本
【二】Session简介
在TensorFlow中,session是沟通tf的桥梁,模型的训练、推理,都需要通过session,session持有graph的引用。tf支持单机与分布式,因此session也分为单机版与分布式版。
【三】session类图
Session ::tensorflow\core\public\session.h
DirectSession ::tensorflow\core\common_runtime\direct_session.h
GrpcSession ::tensorflow\core\distributed_runtime\rpc\grpc_session.h
class DirectSession : public Session --->单机版session
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也很容易,且不影响上层代码。
来源:oschina
链接:https://my.oschina.net/u/3800567/blog/2236918