使用 nn.Transformer 和 TorchText 进行序列到序列建模

原文: https://pytorch.org/tutorials/beginner/transformer_tutorial.html

译者: zanshuxun

本教程展示了如何使用nn.Transformer 模块训练一个seq2seq模型。单击此处下载完整的示例代码

PyTorch 1.2 发布了一个基于论文《Attention is All You Need》的标准transformer模块。transformer模型在很多seq2seq问题上效果更好,且更容易实现并行训练。nn.Transformer模块使用一种注意力机制(最近实现的另一种注意力为 nn.MultiheadAttention)来捕捉输出和输入之间的整体依赖关系。 nn.Transformer做到了高度模块化,其中的单个组件也很容易进行修改和使用(例如本教程中的 nn.TransformerEncoder)。

../_images/transformer_architecture.jpg

定义模型

在本教程中,我们训练了一个nn.TransformerEncoder模型来进行语言建模任务。语言建模任务是指:已有一句话,预测其后续出现某个词或某句话的概率。这句话(一串符号)经过嵌入(embedding)层之后,再使用一个位置编码(positional encoding)层来学习其中的词顺序(详见下一段)。nn.TransformerEncoder由多层 nn.TransformerEncoderLayer 组成。除了输入序列之外,还需要一个正方形的注意力掩码矩阵。因为是用已经出现的词预测后面的词,训练过程中模型不能看到后面已经出现的词,需要用mask矩阵掩盖掉。 为了获得每个单词的预测概率,nn.TransformerEncoder后面会接上一个Linear层和softmax层。

  1. import math
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. class TransformerModel(nn.Module):
  6. def __init__(self, ntoken, ninp, nhead, nhid, nlayers, dropout=0.5):
  7. super(TransformerModel, self).__init__()
  8. from torch.nn import TransformerEncoder, TransformerEncoderLayer
  9. self.model_type = 'Transformer'
  10. self.src_mask = None
  11. self.pos_encoder = PositionalEncoding(ninp, dropout)
  12. encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout)
  13. self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers)
  14. self.encoder = nn.Embedding(ntoken, ninp)
  15. self.ninp = ninp
  16. self.decoder = nn.Linear(ninp, ntoken)
  17. self.init_weights()
  18. def _generate_square_subsequent_mask(self, sz):
  19. mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
  20. mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
  21. return mask
  22. def init_weights(self):
  23. initrange = 0.1
  24. self.encoder.weight.data.uniform_(-initrange, initrange)
  25. self.decoder.bias.data.zero_()
  26. self.decoder.weight.data.uniform_(-initrange, initrange)
  27. def forward(self, src):
  28. if self.src_mask is None or self.src_mask.size(0) != len(src):
  29. device = src.device
  30. mask = self._generate_square_subsequent_mask(len(src)).to(device)
  31. self.src_mask = mask
  32. src = self.encoder(src) * math.sqrt(self.ninp)
  33. src = self.pos_encoder(src)
  34. output = self.transformer_encoder(src, self.src_mask)
  35. output = self.decoder(output)
  36. return output

PositionalEncoding模块能够学到一些序列中符号的相对或绝对位置信息。位置编码层的输出维度与嵌入层相同,两者可以相加。这里我们使用sinecosine函数来学习单词之间的位置信息。

  1. class PositionalEncoding(nn.Module):
  2. def __init__(self, d_model, dropout=0.1, max_len=5000):
  3. super(PositionalEncoding, self).__init__()
  4. self.dropout = nn.Dropout(p=dropout)
  5. pe = torch.zeros(max_len, d_model)
  6. position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
  7. div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
  8. pe[:, 0::2] = torch.sin(position * div_term)
  9. pe[:, 1::2] = torch.cos(position * div_term)
  10. pe = pe.unsqueeze(0).transpose(0, 1)
  11. self.register_buffer('pe', pe)
  12. def forward(self, x):
  13. x = x + self.pe[:x.size(0), :]
  14. return self.dropout(x)

加载数据

训练时使用torchtext中的 Wikitext-2 数据集。下面代码中的 vocab 对象可以将数据集中的符号转为张量,batchify()函数用于生成批次数据,将训练集按照batch_size切分为多个序列,并剔除多余的字符。 例如,当输入序列是字母表时(总长度为 26),设置batch_size为 4,batchify()函数会将输入序列分为 4 个长度为 6 的序列:

使用 nn.Transformer 和 TorchText 进行序列到序列建模 - 图2

不同列对于模型来说是独立的,这意味模型无法学习GF的依赖性,但可以进行更有效的批次训练。

  1. import torchtext
  2. from torchtext.data.utils import get_tokenizer
  3. TEXT = torchtext.data.Field(tokenize=get_tokenizer("basic_english"),
  4. init_token='<sos>',
  5. eos_token='<eos>',
  6. lower=True)
  7. train_txt, val_txt, test_txt = torchtext.datasets.WikiText2.splits(TEXT)
  8. TEXT.build_vocab(train_txt)
  9. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  10. def batchify(data, bsz):
  11. data = TEXT.numericalize([data.examples[0].text])
  12. # Divide the dataset into bsz parts.
  13. nbatch = data.size(0) // bsz
  14. # Trim off any extra elements that wouldn't cleanly fit (remainders).
  15. data = data.narrow(0, 0, nbatch * bsz)
  16. # Evenly divide the data across the bsz batches.
  17. data = data.view(bsz, -1).t().contiguous()
  18. return data.to(device)
  19. batch_size = 20
  20. eval_batch_size = 10
  21. train_data = batchify(train_txt, batch_size)
  22. val_data = batchify(val_txt, eval_batch_size)
  23. test_data = batchify(test_txt, eval_batch_size)

输出:

  1. downloading wikitext-2-v1.zip
  2. extracting

生成输入序列和目标序列

get_batch()函数为transformer 模型生成输入和目标序列,将源数据切分为长度为bptt的块。 对于语言建模任务,模型需要后面出现的单词作为Target。 例如,bptt值为 2、i = 0 时,get_batch()函数会得到以下两个变量:

../_images/transformer_input_target.png

注意,每一块数据的第0维与 Transformer 模型中的S维度一致,第1维是批次尺寸N

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

初始化模型实例

使用下面的超参数创建模型。 词表大小等于 vocab 对象的长度。

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

运行模型

损失函数采用CrossEntropyLoss , 优化器采用SGD 中实现的随机梯度下降法。初始学习率设置为 5.0。 StepLR 用于在不同的迭代伦次(epochs)中调整学习率。 训练时使用 nn.utils.clipgrad_norm 函数将所有梯度进行缩放,来防止发生梯度爆炸。

  1. criterion = nn.CrossEntropyLoss()
  2. lr = 5.0 # learning rate
  3. optimizer = torch.optim.SGD(model.parameters(), lr=lr)
  4. scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)
  5. import time
  6. def train():
  7. model.train() # Turn on the train mode
  8. total_loss = 0.
  9. start_time = time.time()
  10. ntokens = len(TEXT.vocab.stoi)
  11. for batch, i in enumerate(range(0, train_data.size(0) - 1, bptt)):
  12. data, targets = get_batch(train_data, i)
  13. optimizer.zero_grad()
  14. output = model(data)
  15. loss = criterion(output.view(-1, ntokens), targets)
  16. loss.backward()
  17. torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
  18. optimizer.step()
  19. total_loss += loss.item()
  20. log_interval = 200
  21. if batch % log_interval == 0 and batch > 0:
  22. cur_loss = total_loss / log_interval
  23. elapsed = time.time() - start_time
  24. print('| epoch {:3d} | {:5d}/{:5d} batches | '
  25. 'lr {:02.2f} | ms/batch {:5.2f} | '
  26. 'loss {:5.2f} | ppl {:8.2f}'.format(
  27. epoch, batch, len(train_data) // bptt, scheduler.get_lr()[0],
  28. elapsed * 1000 / log_interval,
  29. cur_loss, math.exp(cur_loss)))
  30. total_loss = 0
  31. start_time = time.time()
  32. def evaluate(eval_model, data_source):
  33. eval_model.eval() # Turn on the evaluation mode
  34. total_loss = 0.
  35. ntokens = len(TEXT.vocab.stoi)
  36. with torch.no_grad():
  37. for i in range(0, data_source.size(0) - 1, bptt):
  38. data, targets = get_batch(data_source, i)
  39. output = eval_model(data)
  40. output_flat = output.view(-1, ntokens)
  41. total_loss += len(data) * criterion(output_flat, targets).item()
  42. return total_loss / (len(data_source) - 1)

对训练集最多遍历epochs次。 如果模型在验证集上的损失达到最优,则保存模型。 每一轮训练结束后都会调整学习率。

  1. best_val_loss = float("inf")
  2. epochs = 3 # The number of epochs
  3. best_model = None
  4. for epoch in range(1, epochs + 1):
  5. epoch_start_time = time.time()
  6. train()
  7. val_loss = evaluate(model, val_data)
  8. print('-' * 89)
  9. print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '
  10. 'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),
  11. val_loss, math.exp(val_loss)))
  12. print('-' * 89)
  13. if val_loss < best_val_loss:
  14. best_val_loss = val_loss
  15. best_model = model
  16. scheduler.step()

输出:

  1. | epoch 1 | 200/ 2981 batches | lr 5.00 | ms/batch 29.47 | loss 8.04 | ppl 3112.50
  2. | epoch 1 | 400/ 2981 batches | lr 5.00 | ms/batch 28.38 | loss 6.78 | ppl 882.16
  3. | epoch 1 | 600/ 2981 batches | lr 5.00 | ms/batch 28.38 | loss 6.38 | ppl 589.27
  4. | epoch 1 | 800/ 2981 batches | lr 5.00 | ms/batch 28.40 | loss 6.23 | ppl 508.15
  5. | epoch 1 | 1000/ 2981 batches | lr 5.00 | ms/batch 28.41 | loss 6.12 | ppl 454.63
  6. | epoch 1 | 1200/ 2981 batches | lr 5.00 | ms/batch 28.40 | loss 6.09 | ppl 441.65
  7. | epoch 1 | 1400/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 6.04 | ppl 418.77
  8. | epoch 1 | 1600/ 2981 batches | lr 5.00 | ms/batch 28.41 | loss 6.04 | ppl 421.53
  9. | epoch 1 | 1800/ 2981 batches | lr 5.00 | ms/batch 28.40 | loss 5.96 | ppl 387.98
  10. | epoch 1 | 2000/ 2981 batches | lr 5.00 | ms/batch 28.41 | loss 5.96 | ppl 386.42
  11. | epoch 1 | 2200/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 5.85 | ppl 346.77
  12. | epoch 1 | 2400/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 5.89 | ppl 362.54
  13. | epoch 1 | 2600/ 2981 batches | lr 5.00 | ms/batch 28.42 | loss 5.90 | ppl 364.01
  14. | epoch 1 | 2800/ 2981 batches | lr 5.00 | ms/batch 28.43 | loss 5.80 | ppl 329.20
  15. -----------------------------------------------------------------------------------------
  16. | end of epoch 1 | time: 88.26s | valid loss 5.73 | valid ppl 307.01
  17. -----------------------------------------------------------------------------------------
  18. | epoch 2 | 200/ 2981 batches | lr 4.51 | ms/batch 28.58 | loss 5.79 | ppl 328.13
  19. | epoch 2 | 400/ 2981 batches | lr 4.51 | ms/batch 28.42 | loss 5.77 | ppl 319.25
  20. | epoch 2 | 600/ 2981 batches | lr 4.51 | ms/batch 28.42 | loss 5.60 | ppl 270.79
  21. | epoch 2 | 800/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.63 | ppl 279.91
  22. | epoch 2 | 1000/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.58 | ppl 265.99
  23. | epoch 2 | 1200/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.61 | ppl 273.55
  24. | epoch 2 | 1400/ 2981 batches | lr 4.51 | ms/batch 28.42 | loss 5.63 | ppl 277.59
  25. | epoch 2 | 1600/ 2981 batches | lr 4.51 | ms/batch 28.45 | loss 5.66 | ppl 287.09
  26. | epoch 2 | 1800/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.58 | ppl 266.00
  27. | epoch 2 | 2000/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.61 | ppl 272.58
  28. | epoch 2 | 2200/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.50 | ppl 244.59
  29. | epoch 2 | 2400/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.57 | ppl 262.87
  30. | epoch 2 | 2600/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.58 | ppl 265.65
  31. | epoch 2 | 2800/ 2981 batches | lr 4.51 | ms/batch 28.44 | loss 5.51 | ppl 246.48
  32. -----------------------------------------------------------------------------------------
  33. | end of epoch 2 | time: 88.16s | valid loss 5.53 | valid ppl 253.40
  34. -----------------------------------------------------------------------------------------
  35. | epoch 3 | 200/ 2981 batches | lr 4.29 | ms/batch 28.58 | loss 5.55 | ppl 256.02
  36. | epoch 3 | 400/ 2981 batches | lr 4.29 | ms/batch 28.43 | loss 5.55 | ppl 256.76
  37. | epoch 3 | 600/ 2981 batches | lr 4.29 | ms/batch 28.46 | loss 5.36 | ppl 212.31
  38. | epoch 3 | 800/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.42 | ppl 225.88
  39. | epoch 3 | 1000/ 2981 batches | lr 4.29 | ms/batch 28.46 | loss 5.38 | ppl 217.24
  40. | epoch 3 | 1200/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.41 | ppl 223.82
  41. | epoch 3 | 1400/ 2981 batches | lr 4.29 | ms/batch 28.43 | loss 5.42 | ppl 226.87
  42. | epoch 3 | 1600/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.47 | ppl 238.34
  43. | epoch 3 | 1800/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.41 | ppl 223.13
  44. | epoch 3 | 2000/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.44 | ppl 230.23
  45. | epoch 3 | 2200/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.32 | ppl 205.28
  46. | epoch 3 | 2400/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.40 | ppl 221.60
  47. | epoch 3 | 2600/ 2981 batches | lr 4.29 | ms/batch 28.45 | loss 5.42 | ppl 224.76
  48. | epoch 3 | 2800/ 2981 batches | lr 4.29 | ms/batch 28.44 | loss 5.34 | ppl 209.38
  49. -----------------------------------------------------------------------------------------
  50. | end of epoch 3 | time: 88.18s | valid loss 5.48 | valid ppl 240.75
  51. -----------------------------------------------------------------------------------------

在测试集上评估模型

在测试集上使用保存的最优模型来评估效果。

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

输出:

  1. =========================================================================================
  2. | End of training | test loss 5.39 | test ppl 219.13
  3. =========================================================================================

脚本的总运行时间:(4 分钟 42.167 秒)