【问题标题】:tf.function and tf.while loop in Tensorflow 2.0Tensorflow 2.0 中的 tf.function 和 tf.while 循环
【发布时间】:2019-12-14 04:50:34
【问题描述】:

我正在尝试使用tf.while_loop 并行化循环。正如here 所建议的那样,parallel_iterations 参数在急切模式中没有任何区别。所以我尝试用tf.function 包裹tf.while_loop。但是,添加装饰器后,迭代变量的行为发生了变化。

例如,这段代码有效。

result = np.zeros(10)
iteration = tf.constant(0)
c = lambda i: tf.less(i, 10)
def print_fun(iteration):
    result[iteration] = iteration
    iteration += 1
    return (iteration,)
tf.while_loop(c, print_fun, [iteration])

如果我添加装饰器,就会出现错误。

result = np.zeros(10)
iteration = tf.constant(0)
c = lambda i: tf.less(i, 10)
def print_fun(iteration):
    result[iteration] = iteration
    iteration += 1
    return (iteration,)

@tf.function
def run_graph():
    iteration = tf.constant(0)
    tf.while_loop(c, print_fun, [iteration])

run_graph()

在调试过程中,我发现变量iteration 从张量变为占位符。这是为什么?我应该如何修改代码以消除该错误?

谢谢。

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    您的第一个 sn-p(没有 @tf.function 的那个)中的代码利用 TensorFlow 2 的急切执行来直接操作一个 numpy 数组(即您的外部 iteration 对象)。使用@tf.function,这不起作用,因为@tf.function 试图将您的代码编译成tf.Graph,它不能直接对numpy 数组进行操作(它只能处理tensorflow 张量)。要解决此问题,请使用 tf.Variable 并继续为其切片分配值。

    使用@tf.function,您实际上可以使用更简单的代码来实现,利用@tf.function 的自动Python 到图形转换功能(称为AutoGraph)。您只需编写一个普通的 Python while 循环(使用 tf.less() 代替 < 运算符),while 循环将由 AutoGraph 编译成 tf.while_loop 在引擎盖下。

    代码看起来像:

    result = tf.Variable(np.zeros([10], dtype=np.int32))
    
    @tf.function
    def run_graph():
      i = tf.constant(0, dtype=tf.int32)
      while tf.less(i, 10):
        result[i].assign(i)  # Performance may require tuning here.
        i += 1
    
    run_graph()
    print(result.read_value())
    
    

    【讨论】:

    • 感谢您的回复。如果不调用tf.while_loop,有没有办法设置并行运行的多个迭代?我尝试使用tf.while_loop 的原因是我想在保存每次迭代结果的同时并行化循环。
    • 好问题。在上面的代码中,您可以在末尾添加以下行来检查生成的 tf.Graph 的结构:print(run_graph.get_concrete_function().graph.as_graph_def())。在那里,您可以看到虽然 op 的 parellel_iterations 属性已设置为 10(默认值)。您还可以探索未记录且相对较新的tf.autograph.experimental.set_loop_options() API。参见示例:github.com/tensorflow/tensorflow/blob/master/tensorflow/python/…
    • 感谢您的帮助!我先看看他们。我从 TF 2.0 开始,对 TF 1.0 知之甚少。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多