Transformerを使って自然言語処理してみたいです
Transformerは有用なモデルだ。最近は自然言語処理だけでなく画像処理にも応用されている
でも使うのが難しそうです。
PyTorchには予め必要なモジュールが用意されているため、簡単に使用できるぞ
目次
参考情報
今回は下記の記事を参考に記述しています。
https://pytorch.org/tutorials/beginner/transformer_tutorial.html
動作確認した環境はGoogle Colabになります。設定方法は下記の記事に記述しました。
Transformerとは複数のAttention処理を使用しているモデルになります。Attention Is All You Needで提唱された手法になります。
Transformerが出るまでLSTMなどのモデルが自然言語処理では一般的に使用されていましたが、LSTMなどのモデルは並列実行が難しく、学習、推論時にパフォーマンスを出すのが難しい問題がありました。
TransformerはAttentionをベースにしたモデルにしてLSTMで使われている処理を使わないようにすることで並列実行速度を上げただけでなく、あらゆる自然言語の分野において従来手法を上まる性能を発揮しました。
現在はこのTransformerをベースにして、様々な応用手法が出てきています。BERTもその1種になります。

Attention
まずはAttentionからです。
ここからTransoformerを理解するためにAttentionの説明からTransformerの説明まで行います。
RNNベースの手法の問題点は下記になります。

Attentionは入力が長くても対応できるように下記の処理をしています。
まず入出力単語間のスコアを計算していきます。

スコアの加重平均を計算します。

スコアの加重平均と各隠れそうのベクトルの積の総和をコンテキストベクトルとします。

先程計算したコンテキストベクトルと隠れ層の出力を連結した全結合和にtahとsoftmax関数を適用します。

同様の処理をターゲットの単語をずらして処理をします。

Transformer
ここから本格的にTransformerの説明するぞ
Attentionを一般化して考えます。検索クエリと辞書オブジェクトとして考えます。

実際の処理は下記のようになります。ターゲット単語の隠れ状態をクエリにしてソースの状態を取得する形になります。

先程のqueryとkeyからAttentionの重みを計算できます。Attentionの重みで特定のValueを取得できるため、queryとkeyから特定のValueを取得できることと等価になります。

Self Attention
ターゲットを用意せずに自分自身をターゲットにするSelf Attentionを適用します。

データの依存関係がないので複数queryを使用した並列実行が可能になります。

Encoder部分はこのSelf Attentionを適用します。

EncoderとDecoderの接続部分は通常のAttentionと同一になります。

Decoder部分は未来の値を隠すために-infで置き換えて実行されます。

ここまでの処理では系列の位置情報が考慮されていないので位置情報を考慮できるPositional Encodingを利用します。

sin関数とcosine関数を利用することで周期的な位置ずれを考慮できるため、sin関数とcosine関数を使用します。

Transformerのコード
実際にコードを記述してみるぞ
上記のような複雑なモデルもPyTorchでは予め、モジュールとして用意してくれているため、簡単に実装することができます。
TransformerのEncoderレイヤーが予め実装されているため、それを再利用することによって下記のように簡単に実装できます。
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
Attentionでは並列実行できる利点がある代わりに位置情報が消える問題点があるため、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)
前処理のコード
今回のコードで解くタスクはアルファベットの次の文字を当てるタスクになります。下記の画像のようなイメージでAが入力された際にBを予測する、Gが入力された際はHを予測するような形になります。

今回データはバッチ単位で処理できるような形にはなっていないので、それをバッチ単位で処理できるように変更します。

Wikipediaのデータを簡単に使えるようにしてくれているぞ
wikipediaのデータを用意してくれているので簡単に試すことができます。
通常のWikipediaのデータを使用する場合はハイパーリンクやタグが含まれているので前処理が必要なのですが、このデータはそのような余分なデータをある程度削除しているので簡単に試すことができます。
= = = 2002 – 2006 : Mike Carey ( # 175 – 215 , # <unk> ) = = =
Following Azzarello 's run , writer Mike Carey took over the title , following his <unk> award @-@ winning title Lucifer , set in the Sandman universe . Carey 's run attempted to return John Constantine to his roots , with the title largely set back in London , and featuring many characters from former runs on the title . Mike Carey also has the honour of being the first <unk> to write the <unk> character . His was the second longest run by any single author on the title , second only to Garth Ennis .
import io
import torch
from torchtext.utils import download_from_url, extract_archive
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
url = 'https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip'
test_filepath, valid_filepath, train_filepath = extract_archive(download_from_url(url))
tokenizer = get_tokenizer('basic_english')
vocab = build_vocab_from_iterator(map(tokenizer,
iter(io.open(train_filepath,
encoding="utf8"))))
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_data = data_process(iter(io.open(train_filepath, encoding="utf8")))
val_data = data_process(iter(io.open(valid_filepath, encoding="utf8")))
test_data = data_process(iter(io.open(test_filepath, encoding="utf8")))
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)
入力データとターゲットデータのペアを作成します。入力データがA, G, M, Sの場合はアルファベット順で一つ後のデータになるようにします。

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
学習と評価のためのコード
パラメータの初期設定を行います。`.to(device)`でモデルをGPU用にするかCPU用にするか決定して変換しています。
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)
モデルの学習と評価を行うための関数を設定します。
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_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()
学習が上手く動作すれば下記のようなログがでます。
/usr/local/lib/python3.6/dist-packages/torch/optim/lr_scheduler.py:370: UserWarning: To get the last learning rate computed by the scheduler, please use `get_last_lr()`.
"please use `get_last_lr()`.", UserWarning)
| epoch 1 | 200/ 2928 batches | lr 5.00 | ms/batch 544.99 | loss 8.19 | ppl 3603.26
| epoch 1 | 400/ 2928 batches | lr 5.00 | ms/batch 540.91 | loss 6.90 | ppl 989.88
| epoch 1 | 600/ 2928 batches | lr 5.00 | ms/batch 537.97 | loss 6.45 | ppl 633.91
| epoch 1 | 800/ 2928 batches | lr 5.00 | ms/batch 538.16 | loss 6.31 | ppl 550.20
| epoch 1 | 1000/ 2928 batches | lr 5.00 | ms/batch 545.02 | loss 6.19 | ppl 488.28
| epoch 1 | 1200/ 2928 batches | lr 5.00 | ms/batch 551.32 | loss 6.16 | ppl 474.68
| epoch 1 | 1400/ 2928 batches | lr 5.00 | ms/batch 543.43 | loss 6.12 | ppl 453.51
| epoch 1 | 1600/ 2928 batches | lr 5.00 | ms/batch 548.32 | loss 6.11 | ppl 450.65
| epoch 1 | 1800/ 2928 batches | lr 5.00 | ms/batch 552.12 | loss 6.02 | ppl 412.46
| epoch 1 | 2000/ 2928 batches | lr 5.00 | ms/batch 548.35 | loss 6.02 | ppl 412.68
| epoch 1 | 2200/ 2928 batches | lr 5.00 | ms/batch 554.48 | loss 5.90 | ppl 364.57
| epoch 1 | 2400/ 2928 batches | lr 5.00 | ms/batch 566.11 | loss 5.98 | ppl 394.37
| epoch 1 | 2600/ 2928 batches | lr 5.00 | ms/batch 566.82 | loss 5.96 | ppl 388.47
テストデータの評価をしてみます。
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)
少ないコードでTransformerを実行できました。
PyTorchは予め必要なモジュールが用意されているため簡単にできたぞ
Twitterのデータでポジネガ分析を試したい方は下記の記事をご覧ください。