一、构建集群:
1. 构建集群的代码示例
注:本示例代码使用的 TensorFlow 版本为 1.4.0
# server_distribute.py 文件中构建集群
import tensorflow as tf
"""
这是集群服务的构建
"""
"""
运行命令:
python server_distribute.py --job_name=ps --task_index=0
python server_distribute.py --job_name=ps --task_index=1
python server_distribute.py --job_name=worker --task_index=0
python server_distribute.py --job_name=worker --task_index=1
"""
# 1.配置服务器相关信息,后期搭建集群只需要修改ip地址即可
ps_hosts = ['hosts1:port1', 'hosts2:port2']
work_hosts = ['hosts3:port3', 'hosts4:port4']
# 创建集群
# 为什么是ps和work,因为TensorFlow底层代码中,默认就是使用ps和work分别表示两类不同的工作节点
# ps: 变量/张量的初始化、存储相关节点
# work:变量/张量的计算/运算的相关节点
cluster = tf.train.ClusterSpec({'ps': ps_hosts, 'worker': work_hosts})
# 2.定义一些运行参数(在运行python文件的时候就可以指定这些参数了)
# default_value:可以不给定默认值
tf.app.flags.DEFINE_string(flag_name='job_name', default_value='worker', docstring='One of "ps" or "worker"')
tf.app.flags.DEFINE_integer(flag_name='task_index', default_value=0, docstring='index of task with in the job')
FLAGS = tf.app.flags.FLAGS
# 3.启动服务
def main(_):
print(FLAGS.job_name) # 这个地方会返回集群各个服务器的job_name
print(FLAGS.task_index) # 这个地方会返回集群各个服务器的task_index
server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)
server.join()
if __name__ == '__main__':
# 底层会默认调用main方法
tf.app.run()
二、客户端构建
1. 简单的客户端使用代码示例
# client_use_server.py 使用集群也就是业务端
import tensorflow as tf
import numpy as np
# 启动服务器后,分布式集群就可以使用
"""
python client_use_server.py
"""
# 1.构建图
# with tf.device('/job:ps/task:0/gpu:0'): # 这个是指定在GPU 0上运行
with tf.device('/job:ps/task:0'): # 这个的意思是job使用集群的ps里面的第0个服务器
# 2. 构建数据
x = tf.constant(100, dtype=tf.float32)
# 3.使用另一机器
with tf.device('/job:worker/task:1'): # 这个的意思是job使用集群的work里面的第1个服务器
y = x + 100
# 4.运行,也需要指定运行服务器,代表sess运行的服务器,也就是主节点(master)
# 这里使用第5台机器
with tf.Session(target='grpc://host1:prort1', # 明确在哪个节点运行业务代码
config=tf.ConfigProto(log_device_placement=True,allow_soft_placement=True)) as sess:
ret = sess.run(y)