MultiHeadAttention 在版本之间给出非常不同的值(Pytorch/Tensorflow

青葱年少 pytorch 320

原文标题MultiHeadAttention giving very different values between versions (Pytorch/Tensorflow

我正在尝试重新创建一个用 Pytorch 编写的转换器并使其成为 Tensorflow。一切进展顺利,直到每个版本的 MultiHeadAttention 开始提供截然不同的输出。这两种方法都是多头注意力的实现,如论文“Attention is all you Need”中所述,因此它们应该能够实现相同的输出。

我正在转换

self_attn = nn.MultiheadAttention(dModel, nheads, dropout=dropout)

self_attn = MultiHeadAttention(num_heads=nheads, key_dim=dModel, dropout=dropout)

对于我的测试,dropout 为 0。

我打电话给他们:

self_attn(x,x,x)

其中 x 是一个张量,shape=(10, 128, 50)

正如文档中所预期的那样,Pytorch 版本返回一个元组,(目标序列长度,嵌入维度),维度均为 [10, 128, 50]。

我在让 TensorFlow 版本做同样的事情时遇到了麻烦。使用 Tensorflow 我只能得到一个张量(大小 [10, 128, 50]),它看起来既不是目标序列长度,也不是来自 pytorch 的嵌入维度张量。根据 Tensorflow 文档,我应该得到类似的东西。

我怎样才能让他们以同样的方式运作?我猜我在 Tensorflow 上做错了,但我不知道是什么。

原文链接:https://stackoverflow.com//questions/71906629/multiheadattention-giving-very-different-values-between-versions-pytorch-tensor

回复

我来回复
  • draw的头像
    draw 评论

    nn.MultiheadAttention默认输出带有两个张量的元组:

    • attn_output — result of self-attention operation
    • attn_output_weights — attention weights averaged( ! ) over heads

    同时tf.keras.layers.MultiHeadAttention默认只输出一个张量attention_output(对应pytorch的attn_output)。如果参数return_attention_scores设置为True,也会返回所有头部的注意力权重,例如:

    output, scores = self_attn(x, x, x, return_attention_scores=True)
    

    Tensorscores也应该进行平均,以实现与pytorch的完全对应:

    scores = tf.math.reduce_mean(scores, 1)
    

    重写时请记住,默认情况下(如问题片段)nn.MultiheadAttention期望以表单(seq_length, batch_size, embed_dim)输入,但tf.keras.layers.MultiHeadAttention期望以表单(batch_size, seq_length, embed_dim)输入。

    2年前 0条评论