Tf.Distribute.Strategy:类型错误:无法将<类'tensorflow.python.distribute.values.PerReplica'>的对象转换为张量 [英] tf.distribute.Strategy: TypeError: Failed to convert object of type <class 'tensorflow.python.distribute.values.PerReplica'> to Tensor

查看:34
本文介绍了Tf.Distribute.Strategy:类型错误:无法将<类'tensorflow.python.distribute.values.PerReplica'>的对象转换为张量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据TensorFlow网站https://github.com/tensorflow/docs/blob/r1.15/site/en/guide/distribute_strategy.ipynb上的示例判断,似乎没有关于如何使您的代码适应使用分发策略的资源。我的原始代码包括操作张量,例如tf.expand_dims(x, axis=1)。然而,当使用分发策略时,我得到了上述错误,因为expand_dims()不能在PerReplica对象上工作。有关错误的更多详细信息如下:

内容:PerReplica:{ 0/Replica:0/TASK:0/Device:GPU:0:tensor("IteratorGetNext:0",Shape=(?,2,3),dtype=flat32,Device=/Replica:0/TASK:0/Device:GPU:0), 1/Replica:0/TASK:0/Device:GPU:1:tensor("IteratorGetNext_1:0",Shape=(?,2,3),dtype=Float32,Device=/Replica:0/TASK:0/Device:GPU:1) )

有人知道这个问题的解决方案吗?

推荐答案

PerReplicaObject通常是通过运行strategy.experimental_run_v2/run(...)返回的,您可以将其视为将这些消息对包装在一起的特殊字典: {第i个GPU名称:由第i个GPU返回的张量},在您的所有可用设备中。它看起来像一个字典,但不是真正的字典,类PerReplica为许多用例定义了额外的方法/属性here,例如,在分布式上下文下跨设备减少张量。对于您的案例:

 x = strategy.experimental_run_v2(...)
 if strategy.num_replicas_in_sync > 1:  # x is PerReplica object for multi-devices
    tensors_list = x.values             # a list [x_from_dev_a, x_from_dev_b, ...]
    y = tf.concat(tensors_list, axis=0) # axis=0 at batch dim
 else:
    y = x      # x is a tensor as it is for single device

 tf.expand_dims(y, axis=1)

这篇关于Tf.Distribute.Strategy:类型错误:无法将<类'tensorflow.python.distribute.values.PerReplica'>的对象转换为张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆