首页 > 解决方案 > Tensorflow:在 Eager 模式下慢 7 倍

问题描述

在使用 tensorflow 完成了一个简单的最小化任务(为硬 sigmoid 近似拟合最佳参数)之后,我决定将其从图形模式转换为渴望模式。令我惊讶的是,在急切模式下运行需要更长的时间。

这是代码。

图形模式代码:

import tensorflow as tf
from time import time

beg = time()
a = tf.Variable(-10, name='a', dtype=tf.float32)
b = tf.Variable(10, name='b', dtype=tf.float32)

def g(x):
    return tf.clip_by_value( (x-a)/(b-a), 0, 1)

X = tf.lin_space(-20., 20., 2000)
loss = tf.reduce_sum( tf.square( tf.math.sigmoid(X) - g(X)))
opt = tf.train.AdamOptimizer(learning_rate=1e-3)
train_op = opt.minimize( loss)
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)

    for _ in range( int(1e4)):
        sess.run( train_op)

print( 'Non-eager run in %.1f seconds' %(time()-beg))

印刷Non-eager run in 3.5 seconds

渴望模式代码:

import tensorflow as tf
from time import time

tf.enable_eager_execution()

beg = time()

a = tf.Variable(-10, name='a', dtype=tf.float32)
b = tf.Variable(10, name='b', dtype=tf.float32)

def g(x):
    return tf.clip_by_value( (x-a)/(b-a), 0, 1)

X = tf.lin_space(-20., 20., 2000)

opt = tf.train.AdamOptimizer(learning_rate=1e-3)

for _ in range( int(1e4)):
    with tf.GradientTape() as tape:
        loss = tf.reduce_sum( tf.square( tf.math.sigmoid(X) - g(X)))
        grads = tape.gradient(loss, [a,b])
    opt.apply_gradients(zip(grads, [a,b]), global_step=tf.train.get_or_create_global_step())
print( 'Eager run in %.1f seconds' %(time()-beg))

印刷Eager run in 20.9 seconds

我敢打赌,我的 Eager 代码是次优的,并且tensorflow似乎在其下一个大版本中转向 Eager Execution,我想知道如何优化此代码以使其性能至少与第一个版本相匹配。

标签: pythontensorflowoptimization

解决方案


您在 tensorflow 2.0 中的代码将类似于(请注意,您已经可以尝试每晚构建 tensorflow 2.0(https://pypi.org/project/tf-nightly-2.0-preview/))

import tensorflow as tf
from time import time

tf.enable_eager_execution()

beg = time()


@tf.function
def train():
    a = tf.Variable(-10, name='a', dtype=tf.float32)
    b = tf.Variable(10, name='b', dtype=tf.float32)

    def g(x):
        return tf.clip_by_value((x - a) / (b - a), 0, 1)

    X = tf.lin_space(-20., 20., 2000)
    opt = tf.train.AdamOptimizer(learning_rate=1e-3)

    for _ in range(int(1e4)):
        with tf.GradientTape() as tape:
            loss = tf.reduce_sum(tf.square(tf.math.sigmoid(X) - g(X)))
            grads = tape.gradient(loss, [a, b])
        opt.apply_gradients(
            zip(grads, [a, b]),
            global_step=tf.train.get_or_create_global_step())


train()
print('Eager run in %.1f seconds' % (time() - beg))

请注意tf.contrib.eager.defunand Autograph(在 1.12 及更高版本中可用),它们的基础@tf.session仍在积极开发中并且是实验性的,因此现在实现有点错误;因此,如果它无法运行或速度较慢,可能值得在 Github 上打开一个问题。

在 2.0@tf.session中将合并两者的defun优点autograd


推荐阅读