PyTorch 1.3 Tutorials : テキスト : nn.Transformer と TorchText で Sequence-to-Sequence モデリング

PyTorch 1.3 Tutorials : テキスト : nn.Transformer と TorchText で Sequence-to-Sequence モデリング (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/30/2019 (1.3.1)

* 本ページは、PyTorch 1.3 Tutorials の以下のページを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

テキスト : nn.Transformer と TorchText で Sequence-to-Sequence モデリング

これは nn.Transformer モジュールを使用する sequence-to-sequence モデルをどのように訓練するかについてのチュートリアルです。

PyTorch 1.2 リリースはペーパー Attention is All You Need に基づく標準的な transformer モジュールを含みます。transformer モデルは多くの sequence-to-sequence 問題のために質的に優れている一方でより並列化可能であることが証明されています。nn.Transformer モジュールは入力と出力間のグルーバルな依存性を引き出すために attention メカニズム (もう一つのモジュールは nn.MultiheadAttention として最近実装されました) に完全に依拠しています。nn.Transformer モジュールは今では高位にモジュール化されています、その結果 (このチュートリアルの nn.TransformerEncoder のような) 単一のコンポーネントが容易に適合/構成できます。

 

モデルを定義する

このチュートリアルでは、言語モデリング・タスク上で nn.TransformerEncoder モデルを訓練します。言語モデリング・タスクは単語のシークエンスに従うための与えられた単語 (or 単語のシークエンス) の尤度の確率を割り当てます。トークンのシークエンスが最初に埋め込み層に渡されて、単語の順序を説明するための位置エンコーディング層が従います (モデルの詳細については次のパラグラフを見てください)。nn.TransformerEncoder は nn.TransformerEncoderLayer の複数の層から成ります。入力シークエンスとともに、square attention マスクが必要です、何故ならば nn.TransformerEncoder の self-attention 層はシークエンスの早めの位置に注意を向ける (= attend) ためです。言語モデリング・タスクのためには、未来の位置 (= future position) 上の任意のトークンはマスクされるべきです。実際の単語を持つために、nn.TransformerEncoder モデルの出力は最後の線形層に送られます、これには log-Softmax 関数が続きます。

import math
import torch
import torch.nn as nn
import torch.nn.functional as F

class TransformerModel(nn.Module):

    def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):
        super(TransformerModel, self).__init__()
        from torch.nn import TransformerEncoder, TransformerEncoderLayer
        self.model_type = 'Transformer'
        self.src_mask = None
        self.pos_encoder = PositionalEncoding(ninp, dropout)
        encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)
        self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
        self.encoder = nn.Embedding(ntoken, ninp)
        self.ninp = ninp
        self.decoder = nn.Linear(ninp, ntoken)

        self.init_weights()

    def _generate_square_subsequent_mask(self, sz):
        mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
        mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
        return mask

    def init_weights(self):
        initrange = 0.1
        self.encoder.weight.data.uniform_(-initrange, initrange)
        self.decoder.bias.data.zero_()
        self.decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, src):
        if self.src_mask is None or self.src_mask.size(0) != len(src):
            device = src.device
            mask = self._generate_square_subsequent_mask(len(src)).to(device)
            self.src_mask = mask

        src = self.encoder(src) * math.sqrt(self.ninp)
        src = self.pos_encoder(src)
        output = self.transformer_encoder(src, self.src_mask)
        output = self.decoder(output)
        return output

PositionalEncoding モジュールはセンテンスのトークンの相対的あるいは絶対的位置についてのある情報を注入します。位置エンコーディングは埋め込みと同じ次元を持ちますので、二つは合計できます。ここでは、異なる頻度のサインとコサイン関数を使用します。

class PositionalEncoding(nn.Module):

    def __init__(self, d_model, dropout=0.1, max_len=5000):
        super(PositionalEncoding, self).__init__()
        self.dropout = nn.Dropout(p=dropout)

        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0).transpose(0, 1)
        self.register_buffer('pe', pe)

    def forward(self, x):
        x = x + self.pe[:x.size(0), :]
        return self.dropout(x)

 

データをロードしてバッチ処理する

訓練プロセスは torchtext からの Wikitext-2 データセットを使用します。vocab オブジェクトは訓練データセットに基づいて構築されてトークンを tensor に数値化するために使用されます。シーケンシャルデータから始めて、batchify() 関数はデータセットをカラムに配置し、データがサイズ batch_size のバッチに分割された後に残った任意のトークンを切り取ります。例えば、シークエンスとしてのアルファベット (26 のトータル長) と 4 のバッチサイズにより、アルファベットを長さ 6 の 4 シークエンスに分割するでしょう :

\[
\begin{split}\begin{bmatrix}
\text{A} & \text{B} & \text{C} & \ldots & \text{X} & \text{Y} & \text{Z}
\end{bmatrix}
\Rightarrow
\begin{bmatrix}
\begin{bmatrix}\text{A} \\ \text{B} \\ \text{C} \\ \text{D} \\ \text{E} \\ \text{F}\end{bmatrix} &
\begin{bmatrix}\text{G} \\ \text{H} \\ \text{I} \\ \text{J} \\ \text{K} \\ \text{L}\end{bmatrix} &
\begin{bmatrix}\text{M} \\ \text{N} \\ \text{O} \\ \text{P} \\ \text{Q} \\ \text{R}\end{bmatrix} &
\begin{bmatrix}\text{S} \\ \text{T} \\ \text{U} \\ \text{V} \\ \text{W} \\ \text{X}\end{bmatrix}
\end{bmatrix}\end{split}
\]

これらのカラムはモデルにより独立的として扱われます、これはG と F の依存性は学習できず、しかしより効率的なバッチ処理を可能にします。

import torchtext
from torchtext.data.utils import get_tokenizer
TEXT = torchtext.data.Field(tokenize=get_tokenizer("basic_english"),
                            init_token='',
                            eos_token='',
                            lower=True)
train_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)
TEXT.build_vocab(train_txt)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def batchify(data, bsz):
    data = TEXT.numericalize([data.examples[0].text])
    # Divide the dataset into bsz parts.
    nbatch = data.size(0) // bsz
    # Trim off any extra elements that wouldn't cleanly fit (remainders).
    data = data.narrow(0, 0, nbatch * bsz)
    # Evenly divide the data across the bsz batches.
    data = data.view(bsz, -1).t().contiguous()
    return data.to(device)

batch_size = 20
eval_batch_size = 10
train_data = batchify(train_txt, batch_size)
val_data = batchify(val_txt, eval_batch_size)
test_data = batchify(test_txt, eval_batch_size)
downloading wikitext-2-v1.zip
extracting

 

入力とターゲット・シークエンスを生成する関数

get_batch() 関数は transformer モデルのために入力とターゲット・シークエンスを生成します。それはソースデータを長さ bptt のチャンクに細分します。言語モデリング・タスクのためには、モデルは Target として次の単語を必要とします。例えば、2 の bptt 値で、i = 0 のために次の 2 つの Variable を得るでしょう :

チャンクは次元 0 に沿い、Transformer モデルの S 次元と一貫していることは注意されるべきでしょう。バッチ次元 N は次元 1 に沿います。

bptt = 35
def get_batch(source, i):
    seq_len = min(bptt, len(source) - 1 - i)
    data = source[i:i+seq_len]
    target = source[i+1:i+1+seq_len].view(-1)
    return data, target

 

インスタンスを初期化する

モデルは下のハイパーパラメータでセットアップされます。vocab サイズは vocab オブジェクトの長さに等しいです。

ntokens = len(TEXT.vocab.stoi) # the size of vocabulary
emsize = 200 # embedding dimension
nhid = 200 # the dimension of the feedforward network model in nn.TransformerEncoder
nlayers = 2 # the number of nn.TransformerEncoderLayer in nn.TransformerEncoder
nhead = 2 # the number of heads in the multiheadattention models
dropout = 0.2 # the dropout value
model = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)

 

モデルを実行する

CrossEntropyLoss は損失を追跡するために適用されて SGD は optimizer として確率的勾配降下法を実装します。初期学習率は 5.0 に設定されます。StepLR はエポックを通して学習率を調整するために適用されます。訓練の間、(勾配が) 急上昇するのを防ぐために総ての勾配を一緒にスケールするために nn.utils.clip_grad_norm_ 関数を使用します。

criterion = nn.CrossEntropyLoss()
lr = 5.0 # learning rate
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)

import time
def train():
    model.train() # Turn on the train mode
    total_loss = 0.
    start_time = time.time()
    ntokens = len(TEXT.vocab.stoi)
    for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):
        data, targets = get_batch(train_data, i)
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output.view(-1, ntokens), targets)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
        optimizer.step()

        total_loss += loss.item()
        log_interval = 200
        if batch % log_interval == 0 and batch > 0:
            cur_loss = total_loss / log_interval
            elapsed = time.time() - start_time
            print('| epoch {:3d} | {:5d}/{:5d} batches | '
                  'lr {:02.2f} | ms/batch {:5.2f} | '
                  'loss {:5.2f} | ppl {:8.2f}'.format(
                    epoch, batch, len(train_data) // bptt, scheduler.get_lr()[0],
                    elapsed * 1000 / log_interval,
                    cur_loss, math.exp(cur_loss)))
            total_loss = 0
            start_time = time.time()

def evaluate(eval_model, data_source):
    eval_model.eval() # Turn on the evaluation mode
    total_loss = 0.
    ntokens = len(TEXT.vocab.stoi)
    with torch.no_grad():
        for i in range(0, data_source.size(0) - 1, bptt):
            data, targets = get_batch(data_source, i)
            output = eval_model(data)
            output_flat = output.view(-1, ntokens)
            total_loss += len(data) * criterion(output_flat, targets).item()
    return total_loss / (len(data_source) - 1)

エポックに渡りループします。検証損失がそこまで見た最善であればモデルをセーブします。各エポックの後学習率を調整します。

best_val_loss = float("inf")
epochs = 3 # The number of epochs
best_model = None

for epoch in range(1, epochs + 1):
    epoch_start_time = time.time()
    train()
    val_loss = evaluate(model, val_data)
    print('-' * 89)
    print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '
          'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),
                                     val_loss, math.exp(val_loss)))
    print('-' * 89)

    if val_loss < best_val_loss:
        best_val_loss = val_loss
        best_model = model

    scheduler.step()
| epoch   1 |   200/ 2981 batches | lr 5.00 | ms/batch 29.87 | loss  8.05 | ppl  3141.45
| epoch   1 |   400/ 2981 batches | lr 5.00 | ms/batch 28.63 | loss  6.79 | ppl   892.46
| epoch   1 |   600/ 2981 batches | lr 5.00 | ms/batch 28.65 | loss  6.37 | ppl   585.97
| epoch   1 |   800/ 2981 batches | lr 5.00 | ms/batch 28.65 | loss  6.23 | ppl   509.29
| epoch   1 |  1000/ 2981 batches | lr 5.00 | ms/batch 28.68 | loss  6.12 | ppl   453.05
| epoch   1 |  1200/ 2981 batches | lr 5.00 | ms/batch 28.69 | loss  6.08 | ppl   438.12
| epoch   1 |  1400/ 2981 batches | lr 5.00 | ms/batch 28.67 | loss  6.04 | ppl   419.92
| epoch   1 |  1600/ 2981 batches | lr 5.00 | ms/batch 28.67 | loss  6.05 | ppl   425.16
| epoch   1 |  1800/ 2981 batches | lr 5.00 | ms/batch 28.69 | loss  5.96 | ppl   388.81
| epoch   1 |  2000/ 2981 batches | lr 5.00 | ms/batch 28.70 | loss  5.96 | ppl   388.05
| epoch   1 |  2200/ 2981 batches | lr 5.00 | ms/batch 28.70 | loss  5.85 | ppl   346.81
| epoch   1 |  2400/ 2981 batches | lr 5.00 | ms/batch 28.69 | loss  5.89 | ppl   363.14
| epoch   1 |  2600/ 2981 batches | lr 5.00 | ms/batch 28.69 | loss  5.90 | ppl   363.66
| epoch   1 |  2800/ 2981 batches | lr 5.00 | ms/batch 28.70 | loss  5.80 | ppl   328.75
-----------------------------------------------------------------------------------------
| end of epoch   1 | time: 89.27s | valid loss  5.71 | valid ppl   300.85
-----------------------------------------------------------------------------------------
| epoch   2 |   200/ 2981 batches | lr 4.75 | ms/batch 28.85 | loss  5.80 | ppl   331.87
| epoch   2 |   400/ 2981 batches | lr 4.75 | ms/batch 28.71 | loss  5.77 | ppl   321.40
| epoch   2 |   600/ 2981 batches | lr 4.75 | ms/batch 28.71 | loss  5.60 | ppl   269.78
| epoch   2 |   800/ 2981 batches | lr 4.75 | ms/batch 28.69 | loss  5.63 | ppl   279.53
| epoch   2 |  1000/ 2981 batches | lr 4.75 | ms/batch 28.70 | loss  5.58 | ppl   265.11
| epoch   2 |  1200/ 2981 batches | lr 4.75 | ms/batch 28.72 | loss  5.61 | ppl   273.02
| epoch   2 |  1400/ 2981 batches | lr 4.75 | ms/batch 28.70 | loss  5.62 | ppl   276.32
| epoch   2 |  1600/ 2981 batches | lr 4.75 | ms/batch 28.72 | loss  5.66 | ppl   287.74
| epoch   2 |  1800/ 2981 batches | lr 4.75 | ms/batch 28.71 | loss  5.59 | ppl   268.00
| epoch   2 |  2000/ 2981 batches | lr 4.75 | ms/batch 28.72 | loss  5.62 | ppl   275.85
| epoch   2 |  2200/ 2981 batches | lr 4.75 | ms/batch 28.70 | loss  5.51 | ppl   247.03
| epoch   2 |  2400/ 2981 batches | lr 4.75 | ms/batch 28.71 | loss  5.58 | ppl   264.83
| epoch   2 |  2600/ 2981 batches | lr 4.75 | ms/batch 28.69 | loss  5.59 | ppl   269.00
| epoch   2 |  2800/ 2981 batches | lr 4.75 | ms/batch 28.68 | loss  5.52 | ppl   249.84
-----------------------------------------------------------------------------------------
| end of epoch   2 | time: 89.14s | valid loss  5.59 | valid ppl   266.58
-----------------------------------------------------------------------------------------
| epoch   3 |   200/ 2981 batches | lr 4.51 | ms/batch 28.86 | loss  5.54 | ppl   255.94
| epoch   3 |   400/ 2981 batches | lr 4.51 | ms/batch 28.71 | loss  5.55 | ppl   258.22
| epoch   3 |   600/ 2981 batches | lr 4.51 | ms/batch 28.69 | loss  5.36 | ppl   212.89
| epoch   3 |   800/ 2981 batches | lr 4.51 | ms/batch 28.70 | loss  5.42 | ppl   224.86
| epoch   3 |  1000/ 2981 batches | lr 4.51 | ms/batch 28.70 | loss  5.38 | ppl   216.76
| epoch   3 |  1200/ 2981 batches | lr 4.51 | ms/batch 28.68 | loss  5.41 | ppl   224.39
| epoch   3 |  1400/ 2981 batches | lr 4.51 | ms/batch 28.71 | loss  5.43 | ppl   228.83
| epoch   3 |  1600/ 2981 batches | lr 4.51 | ms/batch 28.70 | loss  5.48 | ppl   239.40
| epoch   3 |  1800/ 2981 batches | lr 4.51 | ms/batch 28.70 | loss  5.41 | ppl   223.12
| epoch   3 |  2000/ 2981 batches | lr 4.51 | ms/batch 28.69 | loss  5.43 | ppl   228.39
| epoch   3 |  2200/ 2981 batches | lr 4.51 | ms/batch 28.70 | loss  5.31 | ppl   202.77
| epoch   3 |  2400/ 2981 batches | lr 4.51 | ms/batch 28.69 | loss  5.38 | ppl   217.70
| epoch   3 |  2600/ 2981 batches | lr 4.51 | ms/batch 28.71 | loss  5.41 | ppl   223.12
| epoch   3 |  2800/ 2981 batches | lr 4.51 | ms/batch 28.71 | loss  5.33 | ppl   207.19
-----------------------------------------------------------------------------------------
| end of epoch   3 | time: 89.11s | valid loss  5.53 | valid ppl   252.61
-----------------------------------------------------------------------------------------

 

モデルをテストデータセットで評価する

テストデータセットで結果を確認するためにベストモデルを適用します。

test_loss = evaluate(best_model, test_data)
print('=' * 89)
print('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(
    test_loss, math.exp(test_loss)))
print('=' * 89)
=========================================================================================
| End of training | test loss  5.44 | test ppl   231.07
=========================================================================================

 
以上