编码器 Transformer 层
在您已经定义了 FeedForwardSubLayer 类的基础上,现在具备了定义 EncoderLayer 类所需的全部组件。回顾一下,编码器层通常由多头注意力机制,以及在子层输入与输出两端都配有层归一化和 dropout 的前馈子层组成。
您之前已经定义的各个类都可直接使用,名称保持不变,同时已为您导入了 torch 和将 torch.nn 命名为 nn。
本练习是课程的一部分
使用 PyTorch 的 Transformer 模型
练习说明
- 完成
__init__方法,实例化MultiHeadAttention、FeedForwardSubLayer,以及两个层归一化。 - 完成
forward()方法,填充多头注意力机制与前馈子层;对于注意力机制,请使用提供的src_mask,并将输入嵌入x分别作为 query、key 和 value 矩阵。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class EncoderLayer(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout):
super().__init__()
# Instantiate the layers
self.self_attn = ____(d_model, num_heads)
self.ff_sublayer = ____(d_model, d_ff)
self.norm1 = ____
self.norm2 = ____
self.dropout = nn.Dropout(dropout)
def forward(self, x, src_mask):
# Complete the forward method
attn_output = self.____
x = self.norm1(x + self.dropout(attn_output))
ff_output = self.____
x = self.norm2(x + self.dropout(ff_output))
return x