PyTorch 1.8 : テキスト : nn.Transformer と TorchText で Seq2Seq モデリング

PyTorch 1.8 チュートリアル : テキスト : nn.Transformer と TorchText で Sequence-to-Sequence モデリング (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 04/18/2021 (1.8.1+cu102)

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

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

 

無料セミナー実施中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマにウェビナー (WEB セミナー) を定期的に開催しています。スケジュールは弊社 公式 Web サイト でご確認頂けます。
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
  • Windows PC のブラウザからご参加が可能です。スマートデバイスもご利用可能です。
クラスキャットは人工知能・テレワークに関する各種サービスを提供しております :

人工知能研究開発支援 人工知能研修サービス テレワーク & オンライン授業を支援
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。)

お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
E-Mail:sales-info@classcat.com  ;  WebSite: https://www.classcat.com/  ;  Facebook

 

テキスト : 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 層はシークエンスの早い位置に注意を向けることが可能にされるだけだからです。言語モデリング・タスクのためには、未来の位置 (= 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.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, src_mask):
        src = self.encoder(src) * math.sqrt(self.ninp)
        src = self.pos_encoder(src)
        output = self.transformer_encoder(src, 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)

 

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

このチュートリアルは Wikitext-2 データセットを生成するために torchtext を利用します。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 io
import torch
from torchtext.datasets import WikiText2
from torchtext.data.utils import get_tokenizer
from collections import Counter
from torchtext.vocab import Vocab

train_iter = WikiText2(split='train')
tokenizer = get_tokenizer('basic_english')
counter = Counter()
for line in train_iter:
    counter.update(tokenizer(line))
vocab = Vocab(counter)

def data_process(raw_text_iter):
  data = [torch.tensor([vocab[token] for token in tokenizer(item)],
                       dtype=torch.long) for item in raw_text_iter]
  return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))

train_iter, val_iter, test_iter = WikiText2()
train_data = data_process(train_iter)
val_data = data_process(val_iter)
test_data = data_process(test_iter)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def batchify(data, bsz):
    # 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_data, batch_size)
val_data = batchify(val_data, eval_batch_size)
test_data = batchify(test_data, eval_batch_size)

 

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

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].reshape(-1)
    return data, target

 

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

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

ntokens = len(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()
    src_mask = model.generate_square_subsequent_mask(bptt).to(device)
    for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):
        data, targets = get_batch(train_data, i)
        optimizer.zero_grad()
        if data.size(0) != bptt:
            src_mask = model.generate_square_subsequent_mask(data.size(0)).to(device)
        output = model(data, src_mask)
        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_last_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.
    src_mask = model.generate_square_subsequent_mask(bptt).to(device)
    with torch.no_grad():
        for i in range(0, data_source.size(0) - 1, bptt):
            data, targets = get_batch(data_source, i)
            if data.size(0) != bptt:
                src_mask = model.generate_square_subsequent_mask(data.size(0)).to(device)
            output = eval_model(data, src_mask)
            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/ 2928 batches | lr 5.00 | ms/batch 28.64 | loss  8.14 | ppl  3422.75
| epoch   1 |   400/ 2928 batches | lr 5.00 | ms/batch 27.85 | loss  6.86 | ppl   957.64
| epoch   1 |   600/ 2928 batches | lr 5.00 | ms/batch 27.77 | loss  6.43 | ppl   621.27
| epoch   1 |   800/ 2928 batches | lr 5.00 | ms/batch 27.88 | loss  6.30 | ppl   546.17
| epoch   1 |  1000/ 2928 batches | lr 5.00 | ms/batch 27.90 | loss  6.19 | ppl   486.20
| epoch   1 |  1200/ 2928 batches | lr 5.00 | ms/batch 27.85 | loss  6.15 | ppl   470.66
| epoch   1 |  1400/ 2928 batches | lr 5.00 | ms/batch 27.84 | loss  6.12 | ppl   454.97
| epoch   1 |  1600/ 2928 batches | lr 5.00 | ms/batch 27.82 | loss  6.11 | ppl   448.39
| epoch   1 |  1800/ 2928 batches | lr 5.00 | ms/batch 27.86 | loss  6.03 | ppl   414.93
| epoch   1 |  2000/ 2928 batches | lr 5.00 | ms/batch 27.90 | loss  6.02 | ppl   412.29
| epoch   1 |  2200/ 2928 batches | lr 5.00 | ms/batch 27.87 | loss  5.91 | ppl   367.85
| epoch   1 |  2400/ 2928 batches | lr 5.00 | ms/batch 27.75 | loss  5.98 | ppl   394.24
| epoch   1 |  2600/ 2928 batches | lr 5.00 | ms/batch 27.90 | loss  5.95 | ppl   384.79
| epoch   1 |  2800/ 2928 batches | lr 5.00 | ms/batch 27.82 | loss  5.88 | ppl   357.29
-----------------------------------------------------------------------------------------
| end of epoch   1 | time: 84.72s | valid loss  5.77 | valid ppl   320.96
-----------------------------------------------------------------------------------------
| epoch   2 |   200/ 2928 batches | lr 4.75 | ms/batch 28.03 | loss  5.86 | ppl   350.16
| epoch   2 |   400/ 2928 batches | lr 4.75 | ms/batch 27.87 | loss  5.85 | ppl   346.71
| epoch   2 |   600/ 2928 batches | lr 4.75 | ms/batch 27.84 | loss  5.67 | ppl   289.05
| epoch   2 |   800/ 2928 batches | lr 4.75 | ms/batch 27.85 | loss  5.70 | ppl   298.91
| epoch   2 |  1000/ 2928 batches | lr 4.75 | ms/batch 27.80 | loss  5.65 | ppl   284.06
| epoch   2 |  1200/ 2928 batches | lr 4.75 | ms/batch 27.90 | loss  5.69 | ppl   295.14
| epoch   2 |  1400/ 2928 batches | lr 4.75 | ms/batch 27.89 | loss  5.69 | ppl   296.57
| epoch   2 |  1600/ 2928 batches | lr 4.75 | ms/batch 27.88 | loss  5.72 | ppl   304.86
| epoch   2 |  1800/ 2928 batches | lr 4.75 | ms/batch 27.92 | loss  5.65 | ppl   284.93
| epoch   2 |  2000/ 2928 batches | lr 4.75 | ms/batch 27.91 | loss  5.67 | ppl   289.24
| epoch   2 |  2200/ 2928 batches | lr 4.75 | ms/batch 27.93 | loss  5.55 | ppl   257.13
| epoch   2 |  2400/ 2928 batches | lr 4.75 | ms/batch 27.90 | loss  5.65 | ppl   283.79
| epoch   2 |  2600/ 2928 batches | lr 4.75 | ms/batch 27.88 | loss  5.65 | ppl   283.80
| epoch   2 |  2800/ 2928 batches | lr 4.75 | ms/batch 27.91 | loss  5.58 | ppl   264.60
-----------------------------------------------------------------------------------------
| end of epoch   2 | time: 84.71s | valid loss  5.66 | valid ppl   286.17
-----------------------------------------------------------------------------------------
| epoch   3 |   200/ 2928 batches | lr 4.51 | ms/batch 28.05 | loss  5.60 | ppl   270.96
| epoch   3 |   400/ 2928 batches | lr 4.51 | ms/batch 27.92 | loss  5.62 | ppl   275.97
| epoch   3 |   600/ 2928 batches | lr 4.51 | ms/batch 27.92 | loss  5.42 | ppl   226.89
| epoch   3 |   800/ 2928 batches | lr 4.51 | ms/batch 27.88 | loss  5.48 | ppl   239.32
| epoch   3 |  1000/ 2928 batches | lr 4.51 | ms/batch 27.92 | loss  5.44 | ppl   229.41
| epoch   3 |  1200/ 2928 batches | lr 4.51 | ms/batch 27.89 | loss  5.48 | ppl   239.59
| epoch   3 |  1400/ 2928 batches | lr 4.51 | ms/batch 27.86 | loss  5.49 | ppl   242.94
| epoch   3 |  1600/ 2928 batches | lr 4.51 | ms/batch 27.87 | loss  5.52 | ppl   249.56
| epoch   3 |  1800/ 2928 batches | lr 4.51 | ms/batch 27.88 | loss  5.47 | ppl   237.80
| epoch   3 |  2000/ 2928 batches | lr 4.51 | ms/batch 27.90 | loss  5.48 | ppl   240.35
| epoch   3 |  2200/ 2928 batches | lr 4.51 | ms/batch 27.90 | loss  5.35 | ppl   211.35
| epoch   3 |  2400/ 2928 batches | lr 4.51 | ms/batch 27.86 | loss  5.46 | ppl   236.18
| epoch   3 |  2600/ 2928 batches | lr 4.51 | ms/batch 27.91 | loss  5.46 | ppl   235.99
| epoch   3 |  2800/ 2928 batches | lr 4.51 | ms/batch 27.90 | loss  5.40 | ppl   221.98
-----------------------------------------------------------------------------------------
| end of epoch   3 | time: 84.73s | valid loss  5.59 | valid ppl   268.81
-----------------------------------------------------------------------------------------

 

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

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

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.50 | test ppl   245.86
=========================================================================================
 

以上