我目前正在尝试使用Transformers实现文本摘要的编码器-解码器架构。因此,我需要在模型的解码器端应用MultiHeadAttention。由于我希望确保模型不会注意到目标序列中未见过的标记,所以我需要使用3D注意力掩码(attn_mask
参数)。
根据文档(https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html),掩码的形状必须为BATCH_SIZE * NUMBER_HEADS,SEQUENCE_LENGTH,SEQUENCE_LENGTH
。这很好,因为它提供了在头之间使用不同注意力的可能性,但在我的情况下不需要...
但文档没有说明张量的第一维应该如何填充,我也找不到在实现中它实际被如何使用...
它是:
[
[2D Attention for Batch 1 for Head 1]
[2D Attention for Batch 2 for Head 1]
...
[2D Attention for Batch 1 for Head 2]
[2D Attention for Batch 2 for Head 2]
...
[2D Attention for Batch n for Head n]
]
或者
[
[2D Attention for Batch 1 for Head 1]
[2D Attention for Batch 1 for Head 2]
...
[2D Attention for Batch 2 for Head 1]
[2D Attention for Batch 2 for Head 2]
...
[2D Attention for Batch n for Head n]
]
希望有人知道,这样就太好了 :)
torch.repeat_interleave
而不是torch.repeat
(https://github.com/pytorch/pytorch/blob/c74c0c571880df886474be297c556562e95c00e0/test/test_nn.py#L5039)。 - cokeSchlumpfrepeat_interleave
似乎是最好的选择。 - Nasheed Yasin