在一台机器上跨多个副本进行同步训练。
继承自:Strategy
用法
tf.distribute.MirroredStrategy(
    devices=None, cross_device_ops=None
)参数
- 
devices设备字符串列表,例如['/gpu:0', '/gpu:1']。如果None,则使用所有可用的 GPU。如果没有找到 GPU,则使用 CPU。
- 
cross_device_ops可选,CrossDeviceOps的后代。如果未设置,则默认使用NcclAllReduce()。如果 NCCL 不可用或者利用特定硬件的特殊实现可用,则可以自定义此设置。
属性
- 
cluster_resolver返回与此策略关联的集群解析器。一般来说,当使用multi-worker tf.distribute策略如tf.distribute.experimental.MultiWorkerMirroredStrategy或tf.distribute.TPUStrategy()时,有一个tf.distribute.cluster_resolver.ClusterResolver与所使用的策略相关联,并且这样的实例由该属性返回。打算拥有关联 tf.distribute.cluster_resolver.ClusterResolver的策略必须设置相关属性,或覆盖此属性;否则,默认返回None。这些策略还应提供有关此属性返回的内容的信息。Single-worker 策略通常没有 tf.distribute.cluster_resolver.ClusterResolver,在这些情况下,此属性将返回None。当用户需要访问集群规范、任务类型或任务 ID 等信息时, tf.distribute.cluster_resolver.ClusterResolver可能很有用。例如,os.environ['TF_CONFIG'] = json.dumps({ 'cluster':{ 'worker':["localhost:12345", "localhost:23456"], 'ps':["localhost:34567"] }, 'task':{'type':'worker', 'index':0} }) # This implicitly uses TF_CONFIG for the cluster and current task info. strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() ... if strategy.cluster_resolver.task_type == 'worker': # Perform something that's only applicable on workers. Since we set this # as a worker above, this block will run on this particular instance. elif strategy.cluster_resolver.task_type == 'ps': # Perform something that's only applicable on parameter servers. Since we # set this as a worker above, this block will not run on this particular # instance.有关详细信息,请参阅 tf.distribute.cluster_resolver.ClusterResolver的 API 文档字符串。
- 
extendedtf.distribute.StrategyExtended与其他方法。
- 
num_replicas_in_sync返回聚合梯度的副本数。
此策略通常用于在具有多个 GPU 的一台机器上进行训练。对于 TPU,请使用 tf.distribute.TPUStrategy 。要将MirroredStrategy 与多个工人一起使用,请参阅tf.distribute.experimental.MultiWorkerMirroredStrategy。
例如,在 MirroredStrategy 下创建的变量是 MirroredVariable 。如果在策略的构造函数参数中没有指定设备,那么它将使用所有可用的 GPU。如果没有找到 GPU,它将使用可用的 CPU。请注意,TensorFlow 将机器上的所有 CPU 视为单个设备,并在内部使用线程进行并行处理。
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
with strategy.scope():
  x = tf.Variable(1.)
x
MirroredVariable:{
  0:<tf.Variable ... shape=() dtype=float32, numpy=1.0>,
  1:<tf.Variable ... shape=() dtype=float32, numpy=1.0>
}在使用分配策略时,所有变量的创建都应该在策略的范围内完成。这将在所有副本之间复制变量,并使用all-reduce 算法使它们保持同步。
在用 tf.function 包装的 MirroredStrategy 中创建的变量仍然是 MirroredVariables 。
x = []
@tf.function  # Wrap the function with tf.function.
def create_variable():
  if not x:
    x.append(tf.Variable(1.))
  return x[0]
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
with strategy.scope():
  _ = create_variable()
  print(x[0])
MirroredVariable:{
  0:<tf.Variable ... shape=() dtype=float32, numpy=1.0>,
  1:<tf.Variable ... shape=() dtype=float32, numpy=1.0>
}experimental_distribute_dataset 可用于在编写自己的训练循环时将数据集分布在副本之间。如果您使用 tf.keras 中可用的 .fit 和 .compile 方法,那么 tf.keras 将为您处理分发。
例如:
my_strategy = tf.distribute.MirroredStrategy()
with my_strategy.scope():
  @tf.function
  def distribute_train_epoch(dataset):
    def replica_fn(input):
      # process input and return result
      return result
    total_result = 0
    for x in dataset:
      per_replica_result = my_strategy.run(replica_fn, args=(x,))
      total_result += my_strategy.reduce(tf.distribute.ReduceOp.SUM,
                                         per_replica_result, axis=None)
    return total_result
  dist_dataset = my_strategy.experimental_distribute_dataset(dataset)
  for _ in range(EPOCHS):
    train_result = distribute_train_epoch(dist_dataset)相关用法
- Python tf.distribute.MirroredStrategy.reduce用法及代码示例
- Python tf.distribute.MirroredStrategy.experimental_distribute_values_from_function用法及代码示例
- Python tf.distribute.MirroredStrategy.scope用法及代码示例
- Python tf.distribute.MirroredStrategy.run用法及代码示例
- Python tf.distribute.MirroredStrategy.experimental_distribute_dataset用法及代码示例
- Python tf.distribute.MirroredStrategy.gather用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy.reduce用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy.scope用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy.experimental_distribute_values_from_function用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy.gather用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy.run用法及代码示例
- Python tf.distribute.MultiWorkerMirroredStrategy.experimental_distribute_dataset用法及代码示例
- Python tf.distribute.OneDeviceStrategy.experimental_distribute_values_from_function用法及代码示例
- Python tf.distribute.TPUStrategy用法及代码示例
- Python tf.distribute.experimental_set_strategy用法及代码示例
- Python tf.distribute.experimental.MultiWorkerMirroredStrategy.gather用法及代码示例
- Python tf.distribute.cluster_resolver.TFConfigClusterResolver用法及代码示例
- Python tf.distribute.experimental.MultiWorkerMirroredStrategy用法及代码示例
- Python tf.distribute.TPUStrategy.experimental_assign_to_logical_device用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.distribute.MirroredStrategy。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
