简体   繁体   English

在 tf 2.x 中以图形模式运行 TensorFlow op

[英]Run TensorFlow op in graph mode in tf 2.x

I would like to benchmark some TensorFlow operations (for example between them or against PyTorch).我想对一些 TensorFlow 操作进行基准测试(例如在它们之间或针对 PyTorch)。 However most of the time I will write something like:但是大多数时候我会写一些类似的东西:

import numpy as np
import tensorflow as tf

tf_device = '/GPU:0'
a = np.random.normal(scale=100, size=shape).astype(np.int64)
b = np.array(7).astype(np.int64)

with tf.device(tf_device):
  a_tf = tf.constant(a)
  b_tf = tf.constant(b)

%timeit tf.math.floormod(a_tf, b_tf)

The problem with this approach is that it does the computation in eager-mode (I think in particular that it has to perform GPU to CPU placement).这种方法的问题在于它在急切模式下进行计算(我认为特别是它必须执行 GPU 到 CPU 放置)。 Eventually, I want to use those ops in a tf.keras model and therefore would like to evaluate their performance in graph mode.最终,我想在tf.keras model 中使用这些操作,因此想评估它们在图形模式下的性能。

What is the preferred way to do it?首选的方法是什么?

My google searches have led to nothing and I don't know how to use sessions like in tf 1.x.我的谷歌搜索没有任何结果,我不知道如何使用 tf 1.x 中的会话。

What you are looking for is tf.function .您正在寻找的是tf.function Check this tutorial and this docs .检查本教程和本文档

As the tutorial says, in TensorFlow 2, eager execution is turned on by default.正如教程所说,在 TensorFlow 2 中,Eager Execution 默认开启。 The user interface is intuitive and flexible (running one-off operations is much easier and faster), but this can come at the expense of performance and deployability.用户界面直观且灵活(一次性操作更容易、更快捷),但这可能会以牺牲性能和可部署性为代价。 To get performant and portable models, use tf.function to make graphs out of your programs.要获得高性能和可移植的模型,请使用 tf.function 从您的程序中制作图表。

Check this code:检查此代码:

import numpy as np
import tensorflow as tf
import timeit

tf_device = '/GPU:0'

shape = [100000]
a = np.random.normal(scale=100, size=shape).astype(np.int64)
b = np.array(7).astype(np.int64)

@tf.function
def experiment(a_tf, b_tf):
  tf.math.floormod(a_tf, b_tf)

with tf.device(tf_device):
  a_tf = tf.constant(a)
  b_tf = tf.constant(b)

# warm up
experiment(a_tf, b_tf)
print("In graph mode:", timeit.timeit(lambda: experiment(a_tf, b_tf), number=10))
print("In eager mode:", timeit.timeit(lambda: tf.math.floormod(a_tf, b_tf), number=10))
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM