当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python tf.compat.v1.distribute.OneDeviceStrategy用法及代码示例


在单个设备上运行的分发策略。

继承自:Strategy

用法

tf.compat.v1.distribute.OneDeviceStrategy(
    device
)

参数

  • device 应放置变量的设备的设备字符串标识符。有关如何使用设备的更多详细信息,请参阅课程文档。示例:"/cpu:0"、"/gpu:0"、"/device:CPU:0"、"/device:GPU:0"

属性

  • cluster_resolver 返回与此策略关联的集群解析器。

    一般来说,当使用multi-worker tf.distribute 策略如tf.distribute.experimental.MultiWorkerMirroredStrategytf.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 文档字符串。

  • extended tf.distribute.StrategyExtended 与其他方法。
  • num_replicas_in_sync 返回聚合梯度的副本数。

使用此策略会将在其范围内创建的任何变量放置在指定设备上。通过此策略分发的输入将被预取到指定的设备。此外,通过strategy.run 调用的任何函数也将被放置在指定的设备上。

此策略的典型用法可能是在切换到实际分发到多个设备/机器的其他策略之前使用 tf.distribute.Strategy API 测试您的代码。

例如:

tf.enable_eager_execution()
strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0")

with strategy.scope():
  v = tf.Variable(1.0)
  print(v.device)  # /job:localhost/replica:0/task:0/device:GPU:0

def step_fn(x):
  return x * 2

result = 0
for i in range(10):
  result += strategy.run(step_fn, args=(i,))
print(result)  # 90

相关用法


注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.compat.v1.distribute.OneDeviceStrategy。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。