原文: https://pytorch.org/tutorials/beginner/transformer_tutorial.html
這是一個(gè)有關(guān)如何訓(xùn)練使用 nn.Transformer 模塊的序列到序列模型的教程。
PyTorch 1.2 版本包括一個(gè)基于紙張的標(biāo)準(zhǔn)變壓器模塊。 事實(shí)證明,該變壓器模型在許多序列間問(wèn)題上具有較高的質(zhì)量,同時(shí)具有更高的可并行性。 nn.Transformer模塊完全依賴于注意力機(jī)制(另一個(gè)最近實(shí)現(xiàn)為 nn.MultiheadAttention 的模塊)來(lái)繪制輸入和輸出之間的全局依存關(guān)系。 nn.Transformer模塊現(xiàn)在已高度模塊化,因此可以輕松地修改/組成單個(gè)組件(例如本教程中的 nn.TransformerEncoder)。
在本教程中,我們?cè)谡Z(yǔ)言建模任務(wù)上訓(xùn)練nn.TransformerEncoder
模型。 語(yǔ)言建模任務(wù)是為給定單詞(或單詞序列)遵循單詞序列的可能性分配概率。 令牌序列首先傳遞到嵌入層,然后傳遞到位置編碼層以說(shuō)明單詞的順序(有關(guān)更多詳細(xì)信息,請(qǐng)參見(jiàn)下一段)。 nn.TransformerEncoder
由多層 nn.TransformerEncoderLayer 組成。 與輸入序列一起,還需要一個(gè)正方形的注意掩碼,因?yàn)?code>nn.TransformerEncoder中的自注意層只允許出現(xiàn)在該序列中的較早位置。 對(duì)于語(yǔ)言建模任務(wù),應(yīng)屏蔽將來(lái)頭寸上的所有標(biāo)記。 為了獲得實(shí)際的單詞,nn.TransformerEncoder
模型的輸出將發(fā)送到最終的 Linear 層,然后是 log-Softmax 函數(shù)。
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
模塊注入一些有關(guān)令牌在序列中的相對(duì)或絕對(duì)位置的信息。 位置編碼的尺寸與嵌入的尺寸相同,因此可以將兩者相加。 在這里,我們使用不同頻率的sine
和cosine
功能。
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)
訓(xùn)練過(guò)程使用torchtext
中的 Wikitext-2 數(shù)據(jù)集。 vocab 對(duì)象是基于訓(xùn)練數(shù)據(jù)集構(gòu)建的,用于將標(biāo)記數(shù)字化為張量。 從順序數(shù)據(jù)開(kāi)始,batchify()
函數(shù)將數(shù)據(jù)集排列為列,以修剪掉數(shù)據(jù)分成大小為batch_size
的批次后剩余的所有令牌。 例如,以字母為序列(總長(zhǎng)度為 26)并且批大小為 4,我們將字母分為 4 個(gè)長(zhǎng)度為 6 的序列:
這些列被模型視為獨(dú)立的,這意味著無(wú)法了解G
和F
的依賴性,但可以進(jìn)行更有效的批處理。
import torchtext
from torchtext.data.utils import get_tokenizer
TEXT = torchtext.data.Field(tokenize=get_tokenizer("basic_english"),
init_token='<sos>',
eos_token='<eos>',
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()
功能為變壓器模型生成輸入和目標(biāo)序列。 它將源數(shù)據(jù)細(xì)分為長(zhǎng)度為bptt
的塊。 對(duì)于語(yǔ)言建模任務(wù),模型需要以下單詞作為Target
。 例如,如果bptt
值為 2,則i
= 0 時(shí),我們將獲得以下兩個(gè)變量:
應(yīng)該注意的是,這些塊沿維度 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
使用下面的超參數(shù)建立模型。 vocab 的大小等于 vocab 對(duì)象的長(zhǎng)度。
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 實(shí)現(xiàn)隨機(jī)梯度下降法作為優(yōu)化器。 初始學(xué)習(xí)率設(shè)置為 5.0。 StepLR 用于通過(guò)歷時(shí)調(diào)整學(xué)習(xí)速率。 在訓(xùn)練過(guò)程中,我們使用 nn.utils.clipgrad_norm 函數(shù)將所有梯度縮放在一起,以防止爆炸。
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)
循環(huán)遍歷。 如果驗(yàn)證損失是迄今為止迄今為止最好的,請(qǐng)保存模型。 在每個(gè)時(shí)期之后調(diào)整學(xué)習(xí)率。
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.47 | loss 8.04 | ppl 3112.50
| epoch 1 | 400/ 2981 batches | lr 5.00 | ms/batch 28.38 | loss 6.78 | ppl 882.16
| epoch 1 | 600/ 2981 batches | lr 5.00 | ms/batch 28.38 | loss 6.38 | ppl 589.27
| epoch 1 | 800/ 2981 batches | lr 5.00 | ms/batch 28.40 | loss 6.23 | ppl 508.15
| epoch 1 | 1000/ 2981 batches | lr 5.00 | ms/batch 28.41 | loss 6.12 | ppl 454.63
| epoch 1 | 1200/ 2981 batches | lr 5.00 | ms/batch 28.40 | loss 6.09 | ppl 441.65
| epoch 1 | 1400/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 6.04 | ppl 418.77
| epoch 1 | 1600/ 2981 batches | lr 5.00 | ms/batch 28.41 | loss 6.04 | ppl 421.53
| epoch 1 | 1800/ 2981 batches | lr 5.00 | ms/batch 28.40 | loss 5.96 | ppl 387.98
| epoch 1 | 2000/ 2981 batches | lr 5.00 | ms/batch 28.41 | loss 5.96 | ppl 386.42
| epoch 1 | 2200/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 5.85 | ppl 346.77
| epoch 1 | 2400/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 5.89 | ppl 362.54
| epoch 1 | 2600/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 5.90 | ppl 364.01
| epoch 1 | 2800/ 2981 batches | lr 5.00 | ms/batch 28.43 | loss 5.80 | ppl 329.20
-----------------------------------------------------------------------------------------
| end of epoch 1 | time: 88.26s | valid loss 5.73 | valid ppl 307.01
-----------------------------------------------------------------------------------------
| epoch 2 | 200/ 2981 batches | lr 4.51 | ms/batch 28.58 | loss 5.79 | ppl 328.13
| epoch 2 | 400/ 2981 batches | lr 4.51 | ms/batch 28.42 | loss 5.77 | ppl 319.25
| epoch 2 | 600/ 2981 batches | lr 4.51 | ms/batch 28.42 | loss 5.60 | ppl 270.79
| epoch 2 | 800/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.63 | ppl 279.91
| epoch 2 | 1000/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.58 | ppl 265.99
| epoch 2 | 1200/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.61 | ppl 273.55
| epoch 2 | 1400/ 2981 batches | lr 4.51 | ms/batch 28.42 | loss 5.63 | ppl 277.59
| epoch 2 | 1600/ 2981 batches | lr 4.51 | ms/batch 28.45 | loss 5.66 | ppl 287.09
| epoch 2 | 1800/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.58 | ppl 266.00
| epoch 2 | 2000/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.61 | ppl 272.58
| epoch 2 | 2200/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.50 | ppl 244.59
| epoch 2 | 2400/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.57 | ppl 262.87
| epoch 2 | 2600/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.58 | ppl 265.65
| epoch 2 | 2800/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.51 | ppl 246.48
-----------------------------------------------------------------------------------------
| end of epoch 2 | time: 88.16s | valid loss 5.53 | valid ppl 253.40
-----------------------------------------------------------------------------------------
| epoch 3 | 200/ 2981 batches | lr 4.29 | ms/batch 28.58 | loss 5.55 | ppl 256.02
| epoch 3 | 400/ 2981 batches | lr 4.29 | ms/batch 28.43 | loss 5.55 | ppl 256.76
| epoch 3 | 600/ 2981 batches | lr 4.29 | ms/batch 28.46 | loss 5.36 | ppl 212.31
| epoch 3 | 800/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.42 | ppl 225.88
| epoch 3 | 1000/ 2981 batches | lr 4.29 | ms/batch 28.46 | loss 5.38 | ppl 217.24
| epoch 3 | 1200/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.41 | ppl 223.82
| epoch 3 | 1400/ 2981 batches | lr 4.29 | ms/batch 28.43 | loss 5.42 | ppl 226.87
| epoch 3 | 1600/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.47 | ppl 238.34
| epoch 3 | 1800/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.41 | ppl 223.13
| epoch 3 | 2000/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.44 | ppl 230.23
| epoch 3 | 2200/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.32 | ppl 205.28
| epoch 3 | 2400/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.40 | ppl 221.60
| epoch 3 | 2600/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.42 | ppl 224.76
| epoch 3 | 2800/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.34 | ppl 209.38
-----------------------------------------------------------------------------------------
| end of epoch 3 | time: 88.18s | valid loss 5.48 | valid ppl 240.75
-----------------------------------------------------------------------------------------
應(yīng)用最佳模型以檢查測(cè)試數(shù)據(jù)集的結(jié)果。
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.39 | test ppl 219.13
=========================================================================================
腳本的總運(yùn)行時(shí)間:(4 分鐘 39.556 秒)
Download Python source code: transformer_tutorial.py
Download Jupyter notebook: transformer_tutorial.ipynb
由獅身人面像畫廊生成的畫廊
更多建議: