第11章注意機構とTransformer
11.7.2. Positionwise Feed-Forward Networks11.7.2 位置ごとのフィードフォワードネットワーク
The positionwise feed-forward network transforms the representation at all the sequence positions using the same MLP. This is why we call it positionwise. In the implementation below, the input
X with shape (batch size, number of time steps or sequence length in tokens, number of hidden units or feature dimension) will be transformed by a two-layer MLP into an output tensor of shape (batch size, number of time steps, ffn_num_outputs).英語のヒント
位置ごとのフィードフォワードネットワークは、系列のすべての位置の表現を同じMLPで変換する。これが位置ごとと呼ぶ理由である。以下の実装では、(バッチサイズ、時間ステップの数あるいはトークン単位の系列の長さ、隠れユニットの数あるいは特徴量の次元)という形状の入力
Xが、2層のMLPによって、(バッチサイズ、時間ステップの数、ffn_num_outputs)という形状の出力テンソルに変換される。class PositionWiseFFN(nn.Module): #@save
"""The positionwise feed-forward network."""
def __init__(self, ffn_num_hiddens, ffn_num_outputs):
super().__init__()
self.dense1 = nn.LazyLinear(ffn_num_hiddens)
self.relu = nn.ReLU()
self.dense2 = nn.LazyLinear(ffn_num_outputs)
def forward(self, X):
return self.dense2(self.relu(self.dense1(X)))The following example shows that the innermost dimension of a tensor changes to the number of outputs in the positionwise feed-forward network. Since the same MLP transforms at all the positions, when the inputs at all these positions are the same, their outputs are also identical.
英語のヒント
次の例は、テンソルの一番内側の次元が、位置ごとのフィードフォワードネットワークの出力の数に変わることを示している。同じMLPがすべての位置で変換するので、これらすべての位置の入力が同じなら、出力も同じになる。
ffn = PositionWiseFFN(4, 8)
ffn.eval()
ffn(torch.ones((2, 3, 4)))[0]tensor([[ 0.6300, 0.7739, 0.0278, 0.2508, -0.0519, 0.4881, -0.4105, 0.5163],
[ 0.6300, 0.7739, 0.0278, 0.2508, -0.0519, 0.4881, -0.4105, 0.5163],
[ 0.6300, 0.7739, 0.0278, 0.2508, -0.0519, 0.4881, -0.4105, 0.5163]],
grad_fn=<SelectBackward0>)