翻译自官网教程:SEQUENCE-TO-SEQUENCE MODELING WITH NN.TRANSFORMER AND TORCHTEXT
本文是关于如何使用nn.Transformer模块训练序列到序列(sequence-to-sequence)模型的教程。
PyTorch 1.2 发布版包括了基于论文Attention is All You
Need的标准transformer
模块。这个transformer
模块被证明在并行度更高的情况下在很多序列到序列的问题中取得了优越的结果。nn.Transformer
模块完全依赖一种注意力机制(目前实现的另一个模块是nn.MultiheadAttention)来抽取输入和输出的全局依赖。nn.Transformer
模块已经被高度模块化使每一个组件(如nn.TransformerEncoder)可以被轻松的调整/组合。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/271715ba2519662bfd84617758ab5129.png)
定义模型
本教程中,我们在语言模型任务上训练nn.TransformerEncoder
模型。语言模型任务是计算一个给定单词(或单词序列)是一个单词序列的后一个单词的概率。符号序列首先传递给嵌入层,随后经过一个位置编码层来获取单词顺序(更多细节见下一段)。nn.TransformerEncoder
包括多层nn.TransformerEncoderLayer。 由于nn.TransformerEncoder
中的自注意力层只允许注意更早位置的序列,因此输入序列需要添加一个方形注意力蒙版(mask)。对于语言模型任务,未来位置的所有符号都应该被屏蔽。为了得到实际单词 nn.TransformerEncoder
模型的输出被输入到线性(Linear)层,然后经过一个log-Softmax函数。
%matplotlib inline
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
模块注入了序列中符号相对或绝对位置的信息。位置编码与嵌入层的维度相同以便它们可以相加。这里,使用不同频率的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)
数据加载并分批
训练过程采用了来自torchtext
的Wikitext-2
数据集。字典对象基于训练集构建并将符号转化成了张量。从序列数据的开端batchify()
函数将数据集排成列,并将数据本分割到大小为batch_size
之后剩余的符号修剪掉。比如,将字母表作为序列(总长度为26),批大小为4,我们将字母表分割成长度为6的4个序列。
[
A
B
C
…
X
Y
Z
]
⇒
[
[
A
B
C
D
E
F
]
[
G
H
I
J
K
L
]
[
M
N
O
P
Q
R
]
[
S
T
U
V
W
X
]
]
\begin{aligned} \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{aligned}
[ABC…XYZ]⇒⎣⎢⎢⎢⎢⎢⎢⎡⎣⎢⎢⎢⎢⎢⎢⎡ABCDEF⎦⎥⎥⎥⎥⎥⎥⎤⎣⎢⎢⎢⎢⎢⎢⎡GHIJKL⎦⎥⎥⎥⎥⎥⎥⎤⎣⎢⎢⎢⎢⎢⎢⎡MNOPQR⎦⎥⎥⎥⎥⎥⎥⎤⎣⎢⎢⎢⎢⎢⎢⎡STUVWX⎦⎥⎥⎥⎥⎥⎥⎤⎦⎥⎥⎥⎥⎥⎥⎤
这些列被模型当作是独立的,也就是说学不到G
和F
之间的依赖,但是可以提高批处理的效率。
由于网络原因数据无法自动下载,可以在这里下载数据并将其解压后保存到.data
文件夹下。
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])
# 将数据集分割成`bsz`批次
nbatch = data.size(0) // bsz
# 将不能整除(剩余)的多余数据裁减掉
data = data.narrow(0, 0, nbatch * bsz)
# 将数据平均分配到`bsz`个批次
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)
生成输入输出序列的函数。
get_batch()
为transformer
模型生成输入和目标序列。它将源数据分割成长度为bptt
的块。对于语言建模任务,模型需要后续的单词作为目标(Target
)。例如,当bptt
值为2时,当i
= 0 可以得到以下两个变量:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7OjyY8AG-1583199257407)(…/_static/img/transformer_input_target.png)]
需要注意,块的沿着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
初始化实例
模型的超参配置如下,词典大小与词典对象的长度相等。
ntokens = len(TEXT.vocab.stoi) # 词汇表的大小
emsize = 200 # 嵌入层维度
nhid = 200 # nn.TransformerEncoder 中的前馈网络模型的维度
nlayers = 2 # nn.TransformerEncoder中nn.TransformerEncoderLayer的层数
nhead = 2 # 多头注意力(multiheadattention)模型头的数量
dropout = 0.2 # dropout 的概率
model = TransformerModel(ntokens, emsize, nhead, nhid, nlayers, dropout).to(device)
运行模型
CrossEntropyLoss被用于跟踪损失,SGD实现了随机梯度下降的优化器。初始学习率设置为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() # 打开训练模式
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 # 训练步次数
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 17.55 | loss 8.05 | ppl 3147.52
| epoch 1 | 400/ 2981 batches | lr 5.00 | ms/batch 17.55 | loss 6.77 | ppl 870.87
| epoch 1 | 600/ 2981 batches | lr 5.00 | ms/batch 17.52 | loss 6.35 | ppl 572.24
| epoch 1 | 800/ 2981 batches | lr 5.00 | ms/batch 17.60 | loss 6.22 | ppl 503.54
| epoch 1 | 1000/ 2981 batches | lr 5.00 | ms/batch 17.51 | loss 6.10 | ppl 446.95
| epoch 1 | 1200/ 2981 batches | lr 5.00 | ms/batch 17.55 | loss 6.08 | ppl 436.12
| epoch 1 | 1400/ 2981 batches | lr 5.00 | ms/batch 17.58 | loss 6.03 | ppl 417.39
| epoch 1 | 1600/ 2981 batches | lr 5.00 | ms/batch 17.60 | loss 6.05 | ppl 422.93
| epoch 1 | 1800/ 2981 batches | lr 5.00 | ms/batch 17.53 | loss 5.96 | ppl 387.47
| epoch 1 | 2000/ 2981 batches | lr 5.00 | ms/batch 17.54 | loss 5.95 | ppl 385.38
| epoch 1 | 2200/ 2981 batches | lr 5.00 | ms/batch 17.54 | loss 5.84 | ppl 344.88
| epoch 1 | 2400/ 2981 batches | lr 5.00 | ms/batch 17.55 | loss 5.89 | ppl 361.41
| epoch 1 | 2600/ 2981 batches | lr 5.00 | ms/batch 17.54 | loss 5.90 | ppl 366.40
| epoch 1 | 2800/ 2981 batches | lr 5.00 | ms/batch 17.53 | loss 5.80 | ppl 329.38
-----------------------------------------------------------------------------------------
| end of epoch 1 | time: 53.82s | valid loss 5.77 | valid ppl 321.25
-----------------------------------------------------------------------------------------
| epoch 2 | 200/ 2981 batches | lr 4.75 | ms/batch 17.28 | loss 5.80 | ppl 328.99
| epoch 2 | 400/ 2981 batches | lr 4.75 | ms/batch 17.59 | loss 5.77 | ppl 320.78
| epoch 2 | 600/ 2981 batches | lr 4.75 | ms/batch 17.59 | loss 5.60 | ppl 270.30
| epoch 2 | 800/ 2981 batches | lr 4.75 | ms/batch 17.62 | loss 5.63 | ppl 279.76
| epoch 2 | 1000/ 2981 batches | lr 4.75 | ms/batch 17.56 | loss 5.58 | ppl 265.22
| epoch 2 | 1200/ 2981 batches | lr 4.75 | ms/batch 17.59 | loss 5.61 | ppl 273.60
| epoch 2 | 1400/ 2981 batches | lr 4.75 | ms/batch 17.57 | loss 5.62 | ppl 276.31
| epoch 2 | 1600/ 2981 batches | lr 4.75 | ms/batch 17.55 | loss 5.65 | ppl 284.88
| epoch 2 | 1800/ 2981 batches | lr 4.75 | ms/batch 17.58 | loss 5.59 | ppl 268.27
| epoch 2 | 2000/ 2981 batches | lr 4.75 | ms/batch 17.57 | loss 5.61 | ppl 273.78
| epoch 2 | 2200/ 2981 batches | lr 4.75 | ms/batch 17.58 | loss 5.50 | ppl 244.37
| epoch 2 | 2400/ 2981 batches | lr 4.75 | ms/batch 17.52 | loss 5.57 | ppl 263.07
| epoch 2 | 2600/ 2981 batches | lr 4.75 | ms/batch 17.51 | loss 5.58 | ppl 266.04
| epoch 2 | 2800/ 2981 batches | lr 4.75 | ms/batch 17.47 | loss 5.51 | ppl 246.15
-----------------------------------------------------------------------------------------
| end of epoch 2 | time: 53.79s | valid loss 5.57 | valid ppl 263.33
-----------------------------------------------------------------------------------------
| epoch 3 | 200/ 2981 batches | lr 4.51 | ms/batch 17.50 | loss 5.54 | ppl 254.23
| epoch 3 | 400/ 2981 batches | lr 4.51 | ms/batch 17.58 | loss 5.54 | ppl 253.84
| epoch 3 | 600/ 2981 batches | lr 4.51 | ms/batch 17.56 | loss 5.35 | ppl 210.40
| epoch 3 | 800/ 2981 batches | lr 4.51 | ms/batch 17.57 | loss 5.41 | ppl 224.32
| epoch 3 | 1000/ 2981 batches | lr 4.51 | ms/batch 17.56 | loss 5.37 | ppl 214.58
| epoch 3 | 1200/ 2981 batches | lr 4.51 | ms/batch 17.56 | loss 5.40 | ppl 222.33
| epoch 3 | 1400/ 2981 batches | lr 4.51 | ms/batch 17.57 | loss 5.43 | ppl 227.91
| epoch 3 | 1600/ 2981 batches | lr 4.51 | ms/batch 17.57 | loss 5.47 | ppl 236.61
| epoch 3 | 1800/ 2981 batches | lr 4.51 | ms/batch 17.59 | loss 5.40 | ppl 220.84
| epoch 3 | 2000/ 2981 batches | lr 4.51 | ms/batch 17.48 | loss 5.42 | ppl 226.76
| epoch 3 | 2200/ 2981 batches | lr 4.51 | ms/batch 17.51 | loss 5.31 | ppl 202.11
| epoch 3 | 2400/ 2981 batches | lr 4.51 | ms/batch 17.56 | loss 5.39 | ppl 219.28
| epoch 3 | 2600/ 2981 batches | lr 4.51 | ms/batch 17.56 | loss 5.42 | ppl 226.57
| epoch 3 | 2800/ 2981 batches | lr 4.51 | ms/batch 17.58 | loss 5.33 | ppl 207.03
-----------------------------------------------------------------------------------------
| end of epoch 3 | time: 53.82s | valid loss 5.48 | valid ppl 239.27
-----------------------------------------------------------------------------------------
使用测试集验证模型
使用测试集测试最佳模型来检查模型效果。
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 218.37
=========================================================================================