【发布时间】:2020-05-18 17:21:40
【问题描述】:
用于文本生成的 tensorflow 官方示例 (https://github.com/tensorflow/docs/blob/master/site/en/tutorials/text/text_generation.ipynb) 在如下定义的循环中运行。文本生成感觉很慢,根据 NVTOP 的说法,它只使用了可用 GPU 资源的一小部分 (15-20%)。
关于如何加快文本生成的任何建议?快速浏览一下 cprofiler 会发现 90% 的时间都花在了 predictions = model(input_eval) 的单行上,所以我认为其他地方不会有很多收获。
此外,Tensorflow/Keras 文档 https://www.tensorflow.org/api_docs/python/tf/keras/Model#predict 建议调用该函数,如下所示...
此方法专为大规模输入的性能而设计。为了 适合一批的少量输入,直接使用 call 建议使用更快的执行速度,例如 model(x) 或 model(x, 训练=假)
关于如何加快文本生成的任何建议?是否可以通过同时生成多行来更好地使用 GPU?
def generate_text(model, start_string):
# Evaluation step (generating text using the learned model)
# Number of characters to generate
num_generate = 1000
# Converting our start string to numbers (vectorizing)
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
# Empty string to store our results
text_generated = []
# Low temperatures results in more predictable text.
# Higher temperatures results in more surprising text.
# Experiment to find the best setting.
temperature = 1.0
# Here batch size == 1
model.reset_states()
for i in range(num_generate):
predictions = model(input_eval)
# remove the batch dimension
predictions = tf.squeeze(predictions, 0)
# using a categorical distribution to predict the character returned by the model
predictions = predictions / temperature
predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()
# We pass the predicted character as the next input to the model
# along with the previous hidden state
input_eval = tf.expand_dims([predicted_id], 0)
text_generated.append(idx2char[predicted_id])
return (start_string + ''.join(text_generated))
【问题讨论】:
-
您是否尝试过在此
generate_text函数中添加@tf.function?您需要修复一些问题才能使其正常工作,但这将使您摆脱急切执行的状态,转而执行更好地编译的图形执行。
标签: python performance tensorflow keras