Transformer代码个人理解(Pytorch)
刚开始接触深度学习的内容,以下代码原文可直接执行,个人理解在代码中以注释的形式给出。
对于Transformer的理解也比较肤浅,后续的内容或新的理解也会继续更新,如有不足之处还请批评指正。
之前对embedding的理解是有问题的,如果在建立embedding时需要嵌入向量与特征之间的关系,那么单单是前期准备工作的难度就是巨大的。实际使用模型中,不可能对所有词汇一一进行特征的标注,也不可能直接实现对特征的关系的量化,故在开始时先根据词典的个数及embedding的维度,给嵌入向量的每个特征生成随机值,再在后续训练中根据不同词汇间的关系修改量化特征参数,这就使得词汇的表示是不可解释的,比起词汇的意义更关注于词汇间的关系,也进一步印证了神经网络的不可解释性。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# nn.与nn.functional.的实际功能是相同的,前者是后者的类封装,functional是函数接口
# 推荐具有学习参数的使用nn.方式,没有学习参数的使用nn.或nn.functional方式
# dropout推荐使用nn.方式
import math, copy, time
from torch.autograd import Variable
import matplotlib.pyplot as plt
import seaborn
seaborn.set_context(context='talk')
# 设置matplotlib的显示风格
class EncoderDecoder(nn.Module):
"""
A standard Encoder-Decoder architecture. Base for this and many other models.
"""
# nn.Module是所有神经网络单元的基类
def __init__(self, encoder, decoder, src_embed, tgt_embed, generator):
super(EncoderDecoder, self).__init__()
# 继承torch的Module和__init__功能,而在__init__中调用了forward函数,
# 故所有Module的子类都会执行forward函数,forward函数的形式:
# def forward(self, input):
# return F.linear(input, self.weight, self.bias)
self.encoder = encoder
self.decoder = decoder
# encoder和decoder需要的传参由后面的类定义
self.src_embed = src_embed
self.tgt_embed = tgt_embed
# 输入输出的embedding形式
self.generator = generator
# 将模型训练结果通过softmax转换为概率值
def forward(self, src, tgt, src_mask, tgt_mask):
"Take in and process masked src and target sequences."
return self.decode(self.encode(src, src_mask), src_mask, tgt, tgt_mask)
def encode(self, src, src_mask):
return self.encoder(self.src_embed(src), src_mask)
def decode(self, memory, src_mask, tgt, tgt_mask):
return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask)
class Generator(nn.Module):
"Define standard linear + softmax generation step."
def __init__(self, d_model, vocab):
# d_model是Decoder输出的大小,vocab是词典大小
super(Generator, self).__init__()
self.proj = nn.Linear(d_model, vocab)
# 根据Decoder的隐状态输出一个词
# nn.Linear()用于设置全连接层,将Decoder输出的d_model个特征作为输入,输出vocab个特征
def forward(self, x):
return F.log_softmax(self.proj(x), dim=-1)
# 将输出通过softmax转换为概率
def clones(module, N):
"Produce N identical layers."
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
# transformer的EncoderLayer和DecoderLayer都是六层,
# 通过clones生成包含N个SubLayer的ModuleList
class Encoder(nn.Module):
"Core encoder is a stack of N layers."
def __init__(self, layer, N):
super(Encoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, mask):
"Pass the input (and mask) through each layer in turn."
for layer in self.layers:
x = layer(x, mask)
# 逐层归一化
return self.norm(x)
class LayerNorm(nn.Module):
"Construct a layer norm module (See citation for details)."
def __init__(self, features, eps=1e-6):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
# nn.Parameter将不可训练的类型Tensor转换为可以训练的Parameter类型,
# 并将Parameter绑定到module中
# torch.ones用于返回一个全为1的张量
self.b_2 = nn.Parameter(torch.zeros(features))
# torch.zeros用于返回一个全为0的张量
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=True)
# 对x这个张量的最内一层维度求均值并保持之前的维度
std = x.std(-1, keepdim=True)
# 对x这个张量的最内一层维度求标准差并保持之前的维度
return self.a_2 * (x - mean) / (std + self.eps) + self.b_2
# 对一层的神经元进行归一化
class SublayerConnection(nn.Module):
"""
A residual connection followed by a layer norm.
Note for code simplicity the norm is first as opposed to last.
"""
def __init__(self, size, dropout):
super(SublayerConnection, self).__init__()
self.norm = LayerNorm(size)
self.dropout = nn.Dropout(dropout)
# dropout用来防止过拟合,首先随机隐藏一半的隐藏层神经元,将输入前向传播
# 继而将得到的损失结果通过修改的网络反向传播,并根据结果更新留下的神经元的参数
# 重复上述过程直到满足损失函数的要求
def forward(self, x, sublayer):
"Apply residual connection to any sublayer with the same size."
return x + self.dropout(sublayer(self.norm(x)))
# 在每两个子层之间使用残差连接防止梯度消失
class EncoderLayer(nn.Module):
"""Encoder is made up of self-attn and feed forward(defined below)."""
def __init__(self, size, self_attn, feed_forward, dropout):
super(EncoderLayer, self).__init__()
self.self_attn = self_attn
# 传参为下文的MultiHeadedAttention(),实现自注意力机制
self.feed_forward = feed_forward
# 传参为下文的PositionwiseFeedForward(),实现全连接前馈网络
self.sublayer = clones(SublayerConnection(size, dropout), 2)
# 复制得到两个连接子层并在后续分别进行子注意力与前馈处理
self.size = size
def forward(self, x, mask):
"Follow Figure 1 (left) for connections."
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask))
return self.sublayer[1](x, self.feed_forward)
class Decoder(nn.Module):
"Generic N layer decoder with masking."
# 同Encoder类,对N层解码器进行归一化
def __init__(self, layer, N):
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def forward(self, x, memory, src_mask, tgt_mask):
for layer in self.layers:
x = layer(x, memory, src_mask, tgt_mask)
return self.norm(x)
class DecoderLayer(nn.Module):
"Decoder is made of self-attn, src-attn, and feed forward (defined below)."
def __init__(self, size, self_attn, src_attn, feed_forward, dropout):
super(DecoderLayer, self).__init__()
self.size = size
self.self_attn = self_attn
self.src_attn = src_attn
# 除了自注意力与前馈网络,解码器还添加了对Encoder输出的自注意力处理src_attn
self.feed_forward = feed_forward
self.sublayer = clones(SublayerConnection(size, dropout), 3)
def forward(self, x, memory, src_mask, tgt_mask):
"Follow Figure 1 (right) for connections."
m = memory
x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask))
x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask))
return self.sublayer[2](x, self.feed_forward)
def subsequent_mask(size):
"Mask out subsequent positions."
attn_shape = (1, size,size)
subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8')
return torch.from_numpy(subsequent_mask) == 0
# 返回上三角为0的torch tensor
# 修正编码器中的自注意力子层,防止当前位置注意到后续序列的位置(Decoder在解码的t时刻不能使用t之后的输入)
plt.figure(figsize=(5,5))
plt.imshow(subsequent_mask(20)[0])
# 显示了修正后的解码情况,只有下三角的位置有值
plt.show()
def attention(query, key, value, mask=None, dropout=None):
"Compute 'Scaled Dot Product Attention'."
# 输入query的形式为(batch_size, heads_num, max_seq_len, d_k),d_k为每个时刻的特征数量
d_k = query.size(-1)
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.sqrt(d_k)
# 点积得到batch_num的时刻下,各个head的注意力得分
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
# 对得分在softmax前进行处理,防止得到的概率数值过小
p_attn = F.softmax(scores, dim = -1)
if dropout is not None:
p_attn = dropout(p_attn)
return torch.matmul(p_attn, value), p_attn
class MultiHeadedAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1):
"Take in model size and number of heads."
super(MultiHeadedAttention, self).__init__()
assert d_model % h == 0
# We assume d_v always equals d_k
self.d_k = d_model // h
self.h = h
self.linears = clones(nn.Linear(d_model, d_model), 4)
self.attn = None
self.dropout = nn.Dropout(p=dropout)
def forward(self, query, key, value, mask=None):
"Implements Figure 2"
if mask is not None:
# Same mask applied to all h heads.
mask = mask.unsqueeze(1)
nbatches = query.size(0)
# 1) Do all the linear projections in batch from d_model => h x d
query, key, value = \
[l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2)
for l, x in zip(self.linears, (query, key, value))]
# 2) Apply attention on all the projected vectors in batch.
x, self.attn = attention(query, key, value, mask=mask, dropout=self.dropout)
# 3) "Concat" using a view and apply a final linear.
x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k)
return self.linears[-1](x)
class PositionwiseFeedForward(nn.Module):
"Implements FFN equation."
def __init__(self, d_model, d_ff, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.Linear(d_model, d_ff)
self.w_2 = nn.Linear(d_ff, d_model)
# 定义两个全连接层,包括两个线性变换及这两层之间的激活函数
# d_model为输入输出维度,d_ff为隐单元个数
self.dropout = nn.Dropout(dropout)
def forward(self, x):
return self.w_2(self.dropout(F.relu(self.w_1(x))))
class Embeddings(nn.Module):
def __init__(self, d_model, vocab):
# d_model为嵌入向量的维度,vocab为词典大小
super(Embeddings, self).__init__()
self.lut = nn.Embedding(vocab, d_model)
# nn.Embedding(num_embeddings, embedding_dim),将字符转换为embedding向量
self.d_model = d_model
# 关键是如何理解embedding,对神经网络的学习至关重要
# 直译"嵌入",实际可理解为针对 每个 包含量化特征参数的 词汇 所生成的 查找表
# 每个表明embedding是一一对应的,既可以将词汇编码为embedding,也可根据embedding得到表示的词汇
# 量化特征参数是embedding与one-hot编码的最大区分,根据特征参数表达词汇意义的相关性及词汇间的关系
# 实际功能就是用张量表示词汇的含义,用张量内携带的参数表明词汇间的关系
def forward(self, x):
return self.lut(x) * math.sqrt(self.d_model)
class PositionalEncoding(nn.Module):
"Implement the PE function."
def __init__(self, d_model, dropout, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
# Compute the positional encodings once in log space.
pe = torch.zeros(max_len, d_model)
position = torch.arange(0., max_len).unsqueeze(1)
# 将position升维方便后续统一处理
div_term = torch.exp(torch.arange(0, d_model, 2) *
-(math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
# 为了判断词汇在序列中的位置信息,对不同维度的embedding生成不同的正余弦曲线表示不同位置
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
# 后续可以通过self.pe调用方法中的参数
def forward(self, x):
x = x + Variable(self.pe[:, :x.size(1)], requires_grad=False)
return self.dropout(x)
plt.figure(figsize=(15, 5))
pe = PositionalEncoding(20, 0)
y = pe.forward(Variable(torch.zeros(1, 100, 20)))
plt.plot(np.arange(100), y[0, :, 4:8].data.numpy())
plt.legend(["dim %d"%p for p in [4,5,6,7]])
def make_model(src_vocab, tgt_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1):
"Helper: Construct a model from hyperparameters."
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
position = PositionalEncoding(d_model, dropout)
model = EncoderDecoder(
Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),
Decoder(DecoderLayer(d_model, c(attn), c(attn), c(ff), dropout), N),
nn.Sequential(Embeddings(d_model, src_vocab), c(position)),
nn.Sequential(Embeddings(d_model, tgt_vocab), c(position)),
Generator(d_model, tgt_vocab)
)
#This was important from their code.
#Initialize parameters with Glorot / fan_avg.
for p in model.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
return model
#Small example model.
tmp_model = make_model(10, 10, 2)
plt.show()