2 回答

TA贡献1810条经验 获得超4个赞
这有效:
with tf.device('/cpu:0'):
# x = tf.get_variable('x', shape=(), initializer=tf.constant_initializer(1), dtype=tf.int32)
x = tf.Variable(1)
op = tf.assign(x, x+1)
with tf.control_dependencies([op]):
x = x + 0
# x = tf.multiply(x, 3)
# x = tf.add(x, 0)
但不总是:
with tf.device('/cpu:0'):
# x = tf.get_variable('x', shape=(), initializer=tf.constant_initializer(1), dtype=tf.int32)
x = tf.Variable(1)
with tf.device('/gpu:0'): # add this line.
op = tf.assign(x, x+1)
with tf.control_dependencies([op]):
x = x + 0
# x = tf.multiply(x, 3)
# x = tf.add(x, 0)
我认为问题出在:
某些操作(例如
x = x + 0
,从读取值Variable
然后添加 0)取决于 的值Variable
,而Variable
由某些分配操作(例如 op = tf.assign(x, x+1))改变。如果没有依赖,这两个操作是并行的。所以在读取 的值时Variable
,不确定是否assign
已经完成。从不同设备传输数据。即使存在依赖关系,它仍然是不确定的。
简而言之,如果所有变量和操作都在同一个设备中,那么with tf.control_dependencies
应该保证op在添加操作之前。
注意:
(以下这些注释并不重要,但可能对您有所帮助)
tf.assign
操作只更新Variable
,不更新Tensor
。当你这样做时
x=x+0
,新的x
变成了Tensor
;但op = tf.assign(x, x+1)
返回Variable
. 所以op
应该始终是确定的,因为它取决于Variable
不会被其他操作改变的当前值。GPU 不支持 int32 变量。当我在我的机器 (tf-gpu1.12) 上运行你的代码片段时,变量是在 CPU 上创建的,但操作是在 GPU 上完成的。您可以通过
config = tf.ConfigProto(log_device_placement=True)
.
添加回答
举报