在 TensorFlow 中向图形节点添加具有副作用的并发计算的正确方法是什么?

What is the correct way of adding concurrent computation with side effect to a graph node in TensorFlow?

我基本上有一个计算图,其操作 A 如下所示:

     |
     o
     |
     A
     |
     o
     |

我想在张量流经 A 时调用额外的计算 B(在本例中为变量赋值):

      |
      o
     / \
    A   B
     \ /
      o
      |

似乎元组允许这样做,但我想知道这是否是最好的方法:

import tensorflow as tf
sess = tf.Session()
v = tf.Variable(0)
sess.run(tf.initialize_all_variables())
A = tf.constant(1)
A, _ = tf.tuple([A, v.assign(2)])
print(sess.run(A))  # prints 1
print(sess.run(v))  # prints 2

所有这些都是在逐层计算的上下文中进行的,其中层权重和其他变量在前向激活通过它们时得到更新。另一种方法可能是将这些更新累积在 fwd_update_ops 列表中,最后调用 sess.run([fwd_update_ops, bwd_update_ops], feed_dict)。还有其他选择吗?最好的方法是什么?

来自@YaroslavBulatov 的评论:

你应该使用 tf.control_dependencies([...]).

例如,要使操作 update_op 依赖于 res = tf.square(A) 你可以这样写:

v = tf.Variable(0, name='v')
A = tf.constant(3, name='A')

update_op = v.assign(2)

with tf.control_dependencies([update_op]):
    res = tf.square(A, name='square')

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    print(sess.run(res))  # prints 9
    print(sess.run(v))  # prints 2, because v got updated

在执行方面,操作tf.square(A)等待直到update_op被执行。

       |
       o
       |  
       A   update_op
       |   /
     square
       |