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

2020-09-07 17:25 更新
原文: https://pytorch.org/tutorials/beginner/transformer_tutorial.html

这是一个有关如何训练使用 nn.Transformer 模块的序列到序列模型的教程。

PyTorch 1.2 版本包括一个基于纸张的标准变压器模块。 事实证明,该变压器模型在许多序列间问题上具有较高的质量,同时具有更高的可并行性。 nn.Transformer模块完全依赖于注意力机制(另一个最近实现为 nn.MultiheadAttention 的模块)来绘制输入和输出之间的全局依存关系。 nn.Transformer模块现在已高度模块化,因此可以轻松地修改/组成单个组件(例如本教程中的 nn.TransformerEncoder)。

../_images/transformer_architecture.jpg

定义模型

在本教程中,我们在语言建模任务上训练nn.TransformerEncoder模型。 语言建模任务是为给定单词(或单词序列)遵循单词序列的可能性分配概率。 令牌序列首先传递到嵌入层,然后传递到位置编码层以说明单词的顺序(有关更多详细信息,请参见下一段)。 nn.TransformerEncoder由多层 nn.TransformerEncoderLayer 组成。 与输入序列一起,还需要一个正方形的注意掩码,因为nn.TransformerEncoder中的自注意层只允许出现在该序列中的较早位置。 对于语言建模任务,应屏蔽将来头寸上的所有标记。 为了获得实际的单词,nn.TransformerEncoder模型的输出将发送到最终的 Linear 层,然后是 log-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)并且批大小为 4,我们将字母分为 4 个长度为 6 的序列:

这些列被模型视为独立的,这意味着无法了解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()功能为变压器模型生成输入和目标序列。 它将源数据细分为长度为bptt的块。 对于语言建模任务,模型需要以下单词作为Target。 例如,如果bptt值为 2,则i = 0 时,我们将获得以下两个变量:

../_images/transformer_input_target.png

应该注意的是,这些块沿维度 0,与 Transformer 模型中的S维度一致。 批次尺寸N沿尺寸 1。

  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 的大小等于 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 用于通过历时调整学习速率。 在训练过程中,我们使用 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)

循环遍历。 如果验证损失是迄今为止迄今为止最好的,请保存模型。 在每个时期之后调整学习率。

  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 分钟 39.556 秒)

Download Python source code: transformer_tutorial.py Download Jupyter notebook: transformer_tutorial.ipynb

由狮身人面像画廊生成的画廊


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号