在摆弄TensorFlow时,我注意到一个相对简单的任务(对我们的3D加速度计数据进行批处理并获取每个时期的总和)的性能相对较差。这是我运行的精髓,一旦我得到了(令人难以置信的漂亮!)Timeline功能:
import numpy as np
import tensorflow as tf
from tensorflow.python.client import timeline
# Some dummy functions to compute "features" from the data
def compute_features( data ):
feature_functions = [
lambda x: test_sum( x, axis = 0 ),
lambda x: test_sum( x, axis = 1 ),
lambda x: test_sum( x, axis = 2 ),
]
return tf.convert_to_tensor( [ f( data ) for f in feature_functions ] )
def test_sum( data, axis = 0 ):
t, v = data
return tf.reduce_sum( v[:, axis] )
# Setup for using Timeline
sess = tf.Session()
run_options = tf.RunOptions( trace_level = tf.RunOptions.FULL_TRACE )
run_metadata = tf.RunMetadata()
# Some magic numbers for our dataset
test_sampling_rate = 5000.0
segment_size = int( 60 * test_sampling_rate )
# Load the dataset
with np.load( 'data.npz' ) as data:
t_raw = data['t']
v_raw = data['v']
# Build the iterator
full_dataset = tf.data.Dataset.from_tensor_slices( (t_raw, v_raw) ).batch( segment_size )
dataset_iterator = full_dataset.make_initializable_iterator()
next_datum = dataset_iterator.get_next()
sess.run( dataset_iterator.initializer )
i = 0
while True:
try:
print( sess.run( compute_features( next_datum ), options = run_options,
run_metadata = run_metadata ) )
# Write Timeline data to a file for analysis later
tl = timeline.Timeline( run_metadata.step_stats )
ctf = tl.generate_chrome_trace_format()
with open( 'timeline_{0}.json'.format( i ), 'w' ) as f:
f.write( ctf )
i += 1
except tf.errors.OutOfRangeError:
break
在Chrome中将其拉出来,我发现在每次迭代中,IteratorGetNext
在绝大部分时间都在吃饭:
Screenshot of Chrome displaying the timeline for one iteration
正如您所看到的,计算的“主要”部分被推入右侧的微小部分,而此周期的绝大部分时间都被卡在IteratorGetNext
中。
我想知道我是否遗漏了任何明显的东西,就我构建我的图形的方式而言,这会导致性能在这一步骤中如此恶劣地降低。我有点难过为什么这个设置表现如此糟糕。
答案 0 :(得分:8)
如果IteratorGetNext
在时间轴中显示为大事件,那么您的模型在输入处理上会出现瓶颈。在这种情况下,管道非常简单,但是将300,000个元素复制到批处理中是瓶颈。您可以通过向数据集定义添加Dataset.prefetch(1)
转换来将此副本移出关键路径:
full_dataset = (tf.data.Dataset.from_tensor_slices((t_raw, v_raw))
.batch(segment_size)
.prefetch(1))
有关更多效果建议,请参阅tensorflow.org上的新Input Pipeline Performance Guide。
PS。在循环中调用compute_features(next_datum)
会导致图形增长,并且循环会随着时间的推移而减慢。如下重写它将更有效:
next_computed_features = compute_features(next_datum)
while True:
try:
print(sess.run(next_computed_features, options=run_options,
run_metadata=run_metadata))
# ...
except tf.errors.OutOfRangeError:
break