• 教程 >
  • 使用 nn.Transformer 和 TorchText 进行序列到序列建模
Shortcuts

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

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

PyTorch 1.2 版本含有一个基于论文 Attention is All You Need 的标准 transformer 模块。 Transformer 模型已被证明在许多序列到序列问题上具有更好的效果,同时具有更高的可并行性。 nn.Transformer模块完全依赖于注意机制(最近实现的另外一个模块nn.MultiheadAttention),以在输入和输出之间绘制全局依赖关系。 nn.Transformer模块现在高度模块化,因此单个组件(如本教程中的nn.TransformerEncoder)可以轻松调整/组合。

../_images/transformer_architecture.jpg

定义模型|

在本教程中,我们将训练nn.TransformerEncoder模型。 语言建模任务是根据一个单词序列对给定的单词(或单词序列)分配一个概率。 首先将一系列 token 传递给嵌入层,然后是考虑单词顺序的位置编码层(有关详细信息,请参阅下一段)。 nn.TransformerEncoder由多层 nn.TransformerEncoderLayer 组成。 与输入序列一起还需要一个方形的注意力掩码,因为nn.TransformerEncoder中的自注意层以只允许关注序列中的较早位置。 对于语言建模任务,应屏蔽未来位置上的任何标记。 为了获得实际的单词,将nn.TransformerEncoder模型的输出发送到最终的 Linear 层,其后是 log-Softmax 函数。

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模块注入一些 Token 在序列中的相对或绝对位置的信息。 位置编码与嵌入具有相同的维度,因此可以求和两者。 在这里,我们使用不同频率的sinecosine函数。

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数据集。 vocab 对象基于训练数据集构建,用于将 Token 数值化为张量。 数据从顺序开始,batchify()函数将数据集排列为列,数据分成大小为batch_size的批次,剩余的所有 Token 去掉。 例如,以字母表为序列(总长度为 26)以及批处理大小为 4,我们将字母表划分为长度为 6 的 4 个序列:

\[\begin{split}\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{split}\]

这些列被模型视为独立列,这意味着无法学习GF的依赖性,但允许更高效的批处理。

import torchtext
from torchtext.data.utils import get_tokenizer
文本 = 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()函数为 transformer 模型生成输入和目标序列。 它将源数据细分成长度为bptt的块。 对于语言建模任务,模型需要以下单词作为Target 例如,bptt值为 2,我们将获得以下两个变量,用于i = 0:

../_images/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

初始化一个实例

模型使用下面的超参数进行设置。 词汇量大小等于 vocab 对象的长度。

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 实现随机梯度下降方法作为优化器。 初始学习速率设置为 5.0。 使用 StepLR 来调整每个 epoch 的学习速率。 在训练期间,我们使用 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() # 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)

循环每个 epoch。 如果验证集损失是目前我们所看到的最好的,则保存模型。 调整每个 epoch 之后的学习速率。

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 124.93 | loss  7.99 | ppl  2949.14
| epoch   1 |   400/ 2981 batches | lr 5.00 | ms/batch 122.26 | loss  6.78 | ppl   878.40
| epoch   1 |   600/ 2981 batches | lr 5.00 | ms/batch 121.36 | loss  6.37 | ppl   582.49
| epoch   1 |   800/ 2981 batches | lr 5.00 | ms/batch 123.27 | loss  6.23 | ppl   505.39
| epoch   1 |  1000/ 2981 batches | lr 5.00 | ms/batch 122.21 | loss  6.11 | ppl   450.76
| epoch   1 |  1200/ 2981 batches | lr 5.00 | ms/batch 122.75 | loss  6.09 | ppl   441.42
| epoch   1 |  1400/ 2981 batches | lr 5.00 | ms/batch 122.13 | loss  6.05 | ppl   422.40
| epoch   1 |  1600/ 2981 batches | lr 5.00 | ms/batch 124.62 | loss  6.05 | ppl   425.40
| epoch   1 |  1800/ 2981 batches | lr 5.00 | ms/batch 126.22 | loss  5.96 | ppl   386.09
| epoch   1 |  2000/ 2981 batches | lr 5.00 | ms/batch 127.20 | loss  5.96 | ppl   388.86
| epoch   1 |  2200/ 2981 batches | lr 5.00 | ms/batch 127.03 | loss  5.85 | ppl   346.01
| epoch   1 |  2400/ 2981 batches | lr 5.00 | ms/batch 127.34 | loss  5.90 | ppl   364.58
| epoch   1 |  2600/ 2981 batches | lr 5.00 | ms/batch 128.40 | loss  5.90 | ppl   365.37
| epoch   1 |  2800/ 2981 batches | lr 5.00 | ms/batch 129.84 | loss  5.80 | ppl   331.25
-----------------------------------------------------------------------------------------
| end of epoch   1 | time: 387.28s | valid loss  5.78 | valid ppl   323.73
-----------------------------------------------------------------------------------------
| epoch   2 |   200/ 2981 batches | lr 4.75 | ms/batch 128.02 | loss  5.79 | ppl   327.90
| epoch   2 |   400/ 2981 batches | lr 4.75 | ms/batch 128.10 | loss  5.77 | ppl   320.35
| epoch   2 |   600/ 2981 batches | lr 4.75 | ms/batch 130.64 | loss  5.60 | ppl   271.34
| epoch   2 |   800/ 2981 batches | lr 4.75 | ms/batch 129.98 | loss  5.64 | ppl   280.59
| epoch   2 |  1000/ 2981 batches | lr 4.75 | ms/batch 131.43 | loss  5.59 | ppl   268.89
| epoch   2 |  1200/ 2981 batches | lr 4.75 | ms/batch 132.91 | loss  5.62 | ppl   276.06
| epoch   2 |  1400/ 2981 batches | lr 4.75 | ms/batch 129.21 | loss  5.63 | ppl   277.27
| epoch   2 |  1600/ 2981 batches | lr 4.75 | ms/batch 128.28 | loss  5.66 | ppl   287.70
| epoch   2 |  1800/ 2981 batches | lr 4.75 | ms/batch 130.00 | loss  5.58 | ppl   266.11
| epoch   2 |  2000/ 2981 batches | lr 4.75 | ms/batch 130.06 | loss  5.62 | ppl   275.50
| epoch   2 |  2200/ 2981 batches | lr 4.75 | ms/batch 131.11 | loss  5.51 | ppl   246.58
| epoch   2 |  2400/ 2981 batches | lr 4.75 | ms/batch 129.66 | loss  5.60 | ppl   269.79
| epoch   2 |  2600/ 2981 batches | lr 4.75 | ms/batch 130.27 | loss  5.59 | ppl   267.55
| epoch   2 |  2800/ 2981 batches | lr 4.75 | ms/batch 128.42 | loss  5.51 | ppl   248.02
-----------------------------------------------------------------------------------------
| end of epoch   2 | time: 400.31s | valid loss  5.57 | valid ppl   263.33
-----------------------------------------------------------------------------------------
| epoch   3 |   200/ 2981 batches | lr 4.51 | ms/batch 130.83 | loss  5.55 | ppl   258.11
| epoch   3 |   400/ 2981 batches | lr 4.51 | ms/batch 129.35 | loss  5.54 | ppl   255.92
| epoch   3 |   600/ 2981 batches | lr 4.51 | ms/batch 129.45 | loss  5.36 | ppl   213.36
| epoch   3 |   800/ 2981 batches | lr 4.51 | ms/batch 128.86 | loss  5.42 | ppl   225.10
| epoch   3 |  1000/ 2981 batches | lr 4.51 | ms/batch 128.21 | loss  5.38 | ppl   216.61
| epoch   3 |  1200/ 2981 batches | lr 4.51 | ms/batch 129.17 | loss  5.42 | ppl   225.47
| epoch   3 |  1400/ 2981 batches | lr 4.51 | ms/batch 128.17 | loss  5.45 | ppl   231.99
| epoch   3 |  1600/ 2981 batches | lr 4.51 | ms/batch 128.30 | loss  5.48 | ppl   240.22
| epoch   3 |  1800/ 2981 batches | lr 4.51 | ms/batch 127.26 | loss  5.41 | ppl   223.74
| epoch   3 |  2000/ 2981 batches | lr 4.51 | ms/batch 128.67 | loss  5.44 | ppl   230.29
| epoch   3 |  2200/ 2981 batches | lr 4.51 | ms/batch 128.46 | loss  5.33 | ppl   206.34
| epoch   3 |  2400/ 2981 batches | lr 4.51 | ms/batch 127.41 | loss  5.41 | ppl   223.09
| epoch   3 |  2600/ 2981 batches | lr 4.51 | ms/batch 134.35 | loss  5.42 | ppl   225.49
| epoch   3 |  2800/ 2981 batches | lr 4.51 | ms/batch 128.57 | loss  5.35 | ppl   210.62
-----------------------------------------------------------------------------------------
| end of epoch   3 | time: 397.84s | valid loss  5.52 | valid ppl   250.16
-----------------------------------------------------------------------------------------

使用测试数据集评估模型|

应用最佳模型以使用测试数据集检查结果。

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.43 | test ppl   228.85
=========================================================================================

脚本总运行时间: (33分24.345秒)

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