始める無料で始める

位置エンコーディングを作成する

トークンを埋め込むことは良い出発点ですが、これだけでは各トークンの系列内での位置情報が含まれていません。これを補うために、Transformer アーキテクチャでは位置エンコーディングを用います。各トークンの位置情報を埋め込みに組み込みます。

次のパラメータを持つ PositionalEncoding クラスを作成します。

  • d_model: 入力埋め込みの次元数
  • max_seq_length: 最大系列長(すべての系列長が同じであればその系列長)

この演習はコースの一部です

PyTorchで学ぶTransformerモデル

コースを見る

演習の手順

  • max_seq_length × d_model のゼロ行列を作成します。
  • 偶数・奇数の位置埋め込み値を作るために、position * div_term に対して sine と cosine の計算を行います。
  • 学習中に pe が学習可能パラメータにならないようにします。
  • 変換した位置埋め込みを入力トークンの埋め込み x に加算します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_seq_length):
        super().__init__()
        # Create a matrix of zeros of dimensions max_seq_length by d_model
        pe = ____
        position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model))
        
        # Perform the sine and cosine calculations
        pe[:, 0::2] = torch.____(position * div_term)
        pe[:, 1::2] = torch.____(position * div_term)
        # Ensure pe isn't a learnable parameter during training
        self.____('____', pe.unsqueeze(0))
        
    def forward(self, x):
        # Add the positional embeddings to the token embeddings
        return ____ + ____[:, :x.size(1)]

pos_encoding_layer = PositionalEncoding(d_model=512, max_seq_length=4)
output = pos_encoding_layer(token_embeddings)
print(output.shape)
print(output[0][0][:10])
コードを編集して実行