【问题标题】:How can I speed up this Keras Attention computation?我怎样才能加快这个 Keras Attention 计算?
【发布时间】:2018-03-08 14:30:46
【问题描述】:

我已经为 AttentiveLSTMCellAttentiveLSTM(RNN) 编写了一个自定义 keras 层,符合 keras 对 RNN 的方法。 Bahdanau 描述了这种注意机制,其中,在编码器/解码器模型中,从编码器的所有输出和解码器的当前隐藏状态创建“上下文”向量。然后,我在每个时间步将上下文向量附加到输入。

该模型用于制作对话代理,但在架构上与 NMT 模型非常相似(类似任务)。

但是,在添加这种注意力机制后,我的网络训练速度减慢了 5 倍,我真的很想知道如何以更高效的方式编写使网络速度减慢的部分代码方式。

这里的计算首当其冲:

h_tm1 = states[0]  # previous memory state
c_tm1 = states[1]  # previous carry state

# attention mechanism

# repeat the hidden state to the length of the sequence
_stm = K.repeat(h_tm1, self.annotation_timesteps)

# multiplty the weight matrix with the repeated (current) hidden state
_Wxstm = K.dot(_stm, self.kernel_w)

# calculate the attention probabilities
# self._uh is of shape (batch, timestep, self.units)
et = K.dot(activations.tanh(_Wxstm + self._uh), K.expand_dims(self.kernel_v))

at = K.exp(et)
at_sum = K.sum(at, axis=1)
at_sum_repeated = K.repeat(at_sum, self.annotation_timesteps)
at /= at_sum_repeated  # vector of size (batchsize, timesteps, 1)

# calculate the context vector
context = K.squeeze(K.batch_dot(at, self.annotations, axes=1), axis=1)

# append the context vector to the inputs
inputs = K.concatenate([inputs, context])

AttentiveLSTMCellcall 方法中(一个时间步长)。

完整代码可以在here找到。如果有必要我提供一些数据和与模型交互的方法,那么我可以这样做。

有什么想法吗?当然,如果这里有什么聪明的地方,我会在 GPU 上进行训练。

【问题讨论】:

  • 你能发布在一些样本训练时期使用tensorflow.python.client.timeline.Timeline 的输出吗?如果没有良好的分析器数据,基本上只是在黑暗中猜测原因。最好收集直接证据。
  • 是的,我可以在一点点 @ely 上解决这个问题。
  • 你分析过你的代码吗?猜测在哪里进行优化可能是一件愚蠢的事。我喜欢 Python line-profiler kernprof,并且你可以使用 Keras 的 TF 工具,比如 TensorBoard

标签: python tensorflow keras vectorization


【解决方案1】:

我建议使用 relu 而不是 tanh 来训练您的模型,因为此操作的计算速度要快得多。这将为您节省训练示例的顺序 * 每个示例的平均序列长度 * 时期数的计算时间。

另外,我会评估附加上下文向量的性能改进,请记住,这会减慢您在其他参数上的迭代周期。如果它没有给您带来太多改进,那么可能值得尝试其他方法。

【讨论】:

    【解决方案2】:

    您修改了适合 CPU 计算的 LSTM 类,但您提到您正在 GPU 上进行训练。

    我建议研究 cudnn-recurrent 实现 或进一步进入使用的tf part。也许你可以在那里扩展代码。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 2021-11-21
      • 2021-08-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多