プリンキピア

第11章注意機構とTransformer

11.7.3. Residual Connection and Layer Normalization11.7.3 残差接続と層正規化

Now let’s focus on the “add & norm” component in Fig. 11.7.1. As we described at the beginning of this section, this is a residual connection immediately followed by layer normalization. Both are key to effective deep architectures.
英語のヒント
では、図11.7.1の「加算と正規化」の部品に注目しよう。この節の初めに説明したように、これは残差接続の直後に層正規化が続くものである。どちらも効果的な深い構造の鍵となる。
In Section 8.5, we explained how batch normalization recenters and rescales across the examples within a minibatch. As discussed in Section 8.5.2.3, layer normalization is the same as batch normalization except that the former normalizes across the feature dimension, thus enjoying benefits of scale independence and batch size independence. Despite its pervasive applications in computer vision, batch normalization is usually empirically less effective than layer normalization in natural language processing tasks, where the inputs are often variable-length sequences.
英語のヒント
8.5節では、バッチ正規化がミニバッチの中の事例にわたって中心化しスケールし直す方法を説明した。8.5.2.3節で論じたように、層正規化は、前者が特徴量の次元にわたって正規化する点を除けばバッチ正規化と同じであり、そのため、スケールに依存しないことと、バッチサイズに依存しないことの利点を享受する。コンピュータビジョンで広く使われているにもかかわらず、入力がしばしば可変長の系列である自然言語処理の課題では、バッチ正規化はふつう層正規化より経験的に効果が低い。
The following code snippet compares the normalization across different dimensions by layer normalization and batch normalization.
英語のヒント
次のコード片は、層正規化とバッチ正規化による、異なる次元にわたる正規化を比べる。
ln = nn.LayerNorm(2)
bn = nn.LazyBatchNorm1d()
X = torch.tensor([[1, 2], [2, 3]], dtype=torch.float32)
# Compute mean and variance from X in the training mode
print('layer norm:', ln(X), '\nbatch norm:', bn(X))
layer norm: tensor([[-1.0000,  1.0000],
        [-1.0000,  1.0000]], grad_fn=<NativeLayerNormBackward0>)
batch norm: tensor([[-1.0000, -1.0000],
        [ 1.0000,  1.0000]], grad_fn=<NativeBatchNormBackward0>)
Now we can implement the AddNorm class using a residual connection followed by layer normalization. Dropout is also applied for regularization.
英語のヒント
これで、残差接続の後に層正規化を続けて、AddNormクラスを実装できる。正則化のためにドロップアウトも当てはめる。
class AddNorm(nn.Module):  #@save
    """The residual connection followed by layer normalization."""
    def __init__(self, norm_shape, dropout):
        super().__init__()
        self.dropout = nn.Dropout(dropout)
        self.ln = nn.LayerNorm(norm_shape)

    def forward(self, X, Y):
        return self.ln(self.dropout(Y) + X)
The residual connection requires that the two inputs are of the same shape so that the output tensor also has the same shape after the addition operation.
英語のヒント
残差接続では、加算の演算の後も出力テンソルが同じ形状をもつように、二つの入力が同じ形状である必要がある。
add_norm = AddNorm(4, 0.5)
shape = (2, 3, 4)
d2l.check_shape(add_norm(torch.ones(shape), torch.ones(shape)), shape)