新方法tf.Variable.read_value()
是TensorFlow 0.12及更高版本中的tf.Variable.ref()
的替代品。
此方法的用例稍微难以解释,并且受到一些缓存行为的驱使,这些缓存行为会导致多个远程变量在不同设备上使用缓存值。比方说,你有下面的代码:
with tf.device("/cpu:0")
v = tf.Variable([[1.]])
with tf.device("/gpu:0")
# The value of `v` will be captured at this point and cached until `m2`
# is computed.
m1 = tf.matmul(v, ...)
with tf.control_dependencies([m1])
# The assign happens (on the GPU) after `m1`, but before `m2` is computed.
assign_op = v.assign([[2.]])
with tf.control_dependencies([assign_op]):
with tf.device("/gpu:0"):
# The initially read value of `v` (i.e. [[1.]]) will be used here,
# even though `m2` is computed after the assign.
m2 = tf.matmul(v, ...)
sess.run(m2)
您可以使用tf.Variable.read_value()
强制TensorFlow稍后再次阅读的变量,它会受到任何控制依赖到位。所以,如果你想看到的分配结果计算m2
时,你会修改程序的最后一块如下:
with tf.control_dependencies([assign_op]):
with tf.device("/gpu:0"):
# The `read_value()` call will cause TensorFlow to transfer the
# new value of `v` from the CPU to the GPU before computing `m2`.
m2 = tf.matmul(v.read_value(), ...)
(需要注意的是,目前,如果所有的OPS都是在同设备,你不会需要使用read_value()
,因为TensorFlow不会将该变量的副本作为同一设备上的操作的输入时使用,这会导致很多混淆。你将一个变量排入队列!这是我们正在为变量增强内存模型的原因之一。)
Tha非常快速和详细的答案。这是非常丰富的信息,我可以很好地理解。 – user270700