プリンキピア

第11章注意機構とTransformer

11.8.3. Vision Transformer Encoder11.8.3 視覚のTransformerのエンコーダ

The MLP of the vision Transformer encoder is slightly different from the positionwise FFN of the original Transformer encoder (see Section 11.7.2). First, here the activation function uses the Gaussian error linear unit (GELU), which can be considered as a smoother version of the ReLU (Hendrycks and Gimpel, 2016). Second, dropout is applied to the output of each fully connected layer in the MLP for regularization.
英語のヒント
視覚のTransformerのエンコーダのMLPは、元のTransformerのエンコーダの位置ごとのFFN(11.7.2節を参照)と少し違う。第一に、ここでは活性化関数にガウス誤差線形ユニット(GELU)を使う。これはReLUのもっとなめらかな版とみなせる(Hendrycks and Gimpel, 2016)。第二に、正則化のため、MLPの各全結合層の出力にドロップアウトを当てはめる。
class ViTMLP(nn.Module):
    def __init__(self, mlp_num_hiddens, mlp_num_outputs, dropout=0.5):
        super().__init__()
        self.dense1 = nn.LazyLinear(mlp_num_hiddens)
        self.gelu = nn.GELU()
        self.dropout1 = nn.Dropout(dropout)
        self.dense2 = nn.LazyLinear(mlp_num_outputs)
        self.dropout2 = nn.Dropout(dropout)

    def forward(self, x):
        return self.dropout2(self.dense2(self.dropout1(self.gelu(
            self.dense1(x)))))
The vision Transformer encoder block implementation just follows the pre-normalization design in Fig. 11.8.1, where normalization is applied right before multi-head attention or the MLP. In contrast to post-normalization (“add & norm” in Fig. 11.7.1), where normalization is placed right after residual connections, pre-normalization leads to more effective or efficient training for Transformers (Baevski and Auli, 2018, Wang et al., 2019, Xiong et al., 2020).
英語のヒント
視覚のTransformerのエンコーダのブロックの実装は、図11.8.1の事前正規化の設計に従うだけである。そこでは、マルチヘッド注意やMLPの直前に正規化が当てはめられる。正規化が残差接続の直後に置かれる事後正規化(図11.7.1の「加算と正規化」)とは対照的に、事前正規化はTransformerのもっと効果的あるいは効率的な訓練につながる(Baevski and Auli, 2018、Wang et al., 2019、Xiong et al., 2020)。
class ViTBlock(nn.Module):
    def __init__(self, num_hiddens, norm_shape, mlp_num_hiddens,
                 num_heads, dropout, use_bias=False):
        super().__init__()
        self.ln1 = nn.LayerNorm(norm_shape)
        self.attention = d2l.MultiHeadAttention(num_hiddens, num_heads,
                                                dropout, use_bias)
        self.ln2 = nn.LayerNorm(norm_shape)
        self.mlp = ViTMLP(mlp_num_hiddens, num_hiddens, dropout)

    def forward(self, X, valid_lens=None):
        X = X + self.attention(*([self.ln1(X)] * 3), valid_lens)
        return X + self.mlp(self.ln2(X))
Just as in Section 11.7.4, no vision Transformer encoder block changes its input shape.
英語のヒント
11.7.4節と同じように、視覚のTransformerのエンコーダのどのブロックも入力の形状を変えない。
X = torch.ones((2, 100, 24))
encoder_blk = ViTBlock(24, 24, 48, 8, 0.5)
encoder_blk.eval()
d2l.check_shape(encoder_blk(X), X.shape)