當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python tf.distribute.experimental.CentralStorageStrategy.experimental_distribute_values_from_function用法及代碼示例


用法

experimental_distribute_values_from_function(
    value_fn
)

參數

  • value_fn 運行以生成值的函數。每個副本都會調用它,並以tf.distribute.ValueContext 作為唯一參數。它必須返回一個張量或可以轉換為張量的類型。

返回

value_fn 生成 tf.distribute.DistributedValues

此函數用於生成 tf.distribute.DistributedValues 以傳遞給 run , reduce 或其他在不使用數據集時采用分布式值的方法。

示例用法:

  1. 每個副本返回常量值:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def value_fn(ctx):
  return tf.constant(1.)
distributed_values = (
     strategy.experimental_distribute_values_from_function(
       value_fn))
local_result = strategy.experimental_local_results(distributed_values)
local_result
(<tf.Tensor:shape=(), dtype=float32, numpy=1.0>,
 <tf.Tensor:shape=(), dtype=float32, numpy=1.0>)
  1. 根據replica_id在數組中分配值:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
array_value = np.array([3., 2., 1.])
def value_fn(ctx):
  return array_value[ctx.replica_id_in_sync_group]
distributed_values = (
     strategy.experimental_distribute_values_from_function(
       value_fn))
local_result = strategy.experimental_local_results(distributed_values)
local_result
(3.0, 2.0)
  1. 使用 num_replicas_in_sync 指定值:
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def value_fn(ctx):
  return ctx.num_replicas_in_sync
distributed_values = (
     strategy.experimental_distribute_values_from_function(
       value_fn))
local_result = strategy.experimental_local_results(distributed_values)
local_result
(2, 2)
  1. 在設備上放置值並分發:
strategy = tf.distribute.TPUStrategy()
worker_devices = strategy.extended.worker_devices
multiple_values = []
for i in range(strategy.num_replicas_in_sync):
  with tf.device(worker_devices[i]):
    multiple_values.append(tf.constant(1.0))

def value_fn(ctx):
  return multiple_values[ctx.replica_id_in_sync_group]

distributed_values = strategy.
  experimental_distribute_values_from_function(
  value_fn)

相關用法


注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.distribute.experimental.CentralStorageStrategy.experimental_distribute_values_from_function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。