[NLP]——The Annotated Transformer(模型篇)

目录

  • 背景
  • 模型
    • Encoder
    • Decoder
    • Attention
    • FFN
    • Embeddings
    • Positional Encoding(sinusoidal version)
    • 完整模型
  • 实战
  • 参考

背景

有很多为了减少序列计算而引出的模型:Neural GPU\ByteNet\ConvS2S,它们使用卷积神经网络来并行化的计算。然而,这些模型的计算次数随着输入和输出间的距离增长而增长,带来了长期依赖问题。Transformer的计算次数是常数,但是是以减弱了位置信息为代价,具体的,它使用Multi-Head Attention来实现。

self-attention应用广泛,Transformer是第一个完全依赖于self-attention的transduction model,关于transduction model,感觉就是通过已观察的去预测未被观察的,特别用于语言模型、RNNs model。

模型

大多数的神经序列transduction模型使用encoder将输入序列 ( x 1 , . . . x n ) (x_1,...x_n) (x1,...xn)映射到 ( z 1 , . . . z n ) ( z ) (z_1,...z_n) (z) (z1,...zn)(z)给定z,使用decoder一步一生成,Transformer也如此。

Encoder

Encoder由6个一致Encoder Layer组成,所以定义了一个Encoder类以后,可以使用clones函数来复制Encoder Layer:

def clones(module, N):
    "Produce N identical layers."
    return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
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)

每一个Encoder Layer由两个sub-layers组成,每一个sub-layers的输出需要被送入到SublayerConnection进行 1. LayerNormalization(由单独的类LayerNorm完成) 2. ResidualConnection(定义在SublayerConnection类里面)

class LayerNorm(nn.Module):
    "Construct a layernorm module (See citation for details)."
    def __init__(self, features, eps=1e-6):
        super(LayerNorm, self).__init__()
        self.a_2 = nn.Parameter(torch.ones(features))
        self.b_2 = nn.Parameter(torch.zeros(features))
        self.eps = eps

    def forward(self, x):
        mean = x.mean(-1, keepdim=True)
        std = x.std(-1, keepdim=True)
        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)

    def forward(self, x, sublayer):
        "Apply residual connection to any sublayer with the same size."
        return x + self.dropout(sublayer(self.norm(x)))

回到EncoderLayer,两个sub-layers分别是self-attention mechanism 和 position-wise fully connected feed-forward network

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
        self.feed_forward = feed_forward
        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)) # 传入一个输入(x) 和 一个映射函数(sublayer)
        return self.sublayer[1](x, self.feed_forward)

Decoder

Decoder也由6个一致的DecoderLayer层组成

class Decoder(nn.Module):
    "Generic N layer decoder with masking."
    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)

DecoderLayer和EncoderLayer有所不同,DecoderLayer由三个sub-layers组成,分别是Masked Multi-Head Attention、Multi-Head Attention和position-wise fully connected feed-forward network。特别说明的是:1. Masked Multi-Head Attention的输入是mask之后的x(用于掩盖当前要预测单词以及之后的信息) 2. Multi-Head Attention的Q\K\V中,Q是由Masked Multi-Head Attention生成,K和V是从encoder中来的。
同样的,每经过一个子层,需要通过SublayerConnection进行 1. LayerNormalization 2. ResidualConnection

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
        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)

其中mask函数为:

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

每一行代表target句子中的一个单词,每一列代表对应单词能够看到的单词。如第1个单词只能看到第1个,第2个单词能看到1、2,第3个单词能看到1、2、3…
[NLP]——The Annotated Transformer(模型篇)_第1张图片

Attention

这里的Attention又被称为Scaled Dot-Product Attention,首先使用Q(bs, sent_len, d_k)和K(bs, sent_len, d_k)来计算weight(bs, sent_len, sent_len),再用weight对V(bs, sent_len, d_v)进行加权求和得到attention过后的向量表示(bs, sent_len, d_v)。

A t t e n t i o n ( Q , K , V ) = s o f t m a x ( Q K T / d k ) V Attention(Q,K,V) = softmax(QK^T/\sqrt{d_k})V Attention(Q,K,V)=softmax(QKT/dk )V

def attention(query, key, value, mask=None, dropout=None):
    "Compute 'Scaled Dot Product Attention'"
    # query: ds, sent, d_k
    d_k = query.size(-1)
    scores = torch.matmul(query, key.transpose(-2, -1)) \
             / math.sqrt(d_k) # ds, sent, sent
    if mask is not None:
        scores = scores.masked_fill(mask == 0, -1e9)
    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

关于为什么要做缩放,可参照here
大概就是:如果 d k \sqrt{d_k} dk 很大,q和k点积的数量级增长就很大,进一步导致softmax函数的梯度很小。而关于为什么点积的数量级会随着 d k d_k dk变大,假设q和k的成分是均值为0、方差为1的独立随机变量,那么它们的点积 q ⋅ k = ∑ i = 1 d k q i k i q·k=\sum_{i=1}^{d_k}q_ik_i qk=i=1dkqiki的均值为0,方差就为 d k d_k dk,所以要缩放。

这里的attention还是多头的,被称为Multi-head attention。称上面attention函数的输出是一个head,代表一个子空间,现在通过h=8个映射矩阵,得到8组Q、K和V输入,进一步得到8个head,再拼接,再映射,得到输出。
M u l t i H e a d ( Q , K , V ) = C o n c a t ( h e a d 1 , . . . , h e a d 8 ) W o MultiHead(Q,K,V)=Concat(head_1,...,head_8)W^o MultiHead(Q,K,V)=Concat(head1,...,head8)Wo
w h e r e h e a d i = A t t e t i o n ( Q W i Q , K W i K , V W i V ) where head_i = Attetion(QW_i^Q,KW_i^K,VW_i^V) whereheadi=Attetion(QWiQ,KWiK,VWiV)

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) # 这里的4不代表4个头,而是分别代表上面公式中的W_Q\W_K\W_V
W_O        self.attn = None
        self.dropout = nn.Dropout(p=dropout)
        
    def forward(self, query, key, value, mask=None):
    	# query; bs, sent, d_model
        "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_k 
        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)

上面代码理解为:

[NLP]——The Annotated Transformer(模型篇)_第2张图片

FFN

Position-wise Feed Forward Networks:
F F N ( x ) = m a x ( 0 , x W 1 + b 1 ) W 2 + b 2 FFN(x) = max(0, xW_1+b_1)W_2+b_2 FFN(x)=max(0,xW1+b1)W2+b2

其中, W 1 W_1 W1:d_model=512 x d_ff=2048; W 2 W_2 W2:d_ff = 2048 x d_model = 512.

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)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        return self.w_2(self.dropout(F.relu(self.w_1(x))))

Embeddings

为什么要乘 d m o d e l \sqrt{d_{model}} dmodel ?

class Embeddings(nn.Module):
    def __init__(self, d_model, vocab):
        super(Embeddings, self).__init__()
        self.lut = nn.Embedding(vocab, d_model)
        self.d_model = d_model

    def forward(self, x):
        return self.lut(x) * math.sqrt(self.d_model)

Positional Encoding(sinusoidal version)

PE的公式:
P E ( p o s , 2 i ) = s i n ( p o s / 1000 0 2 i / d m o d e l ) PE(pos,2i) = sin(pos/10000^{2i/d_{model}}) PE(pos,2i)=sin(pos/100002i/dmodel)
P E ( p o s , 2 i + 1 ) = c o s ( p o s / 1000 0 2 i / d m o d e l ) PE(pos,2i+1) = cos(pos/10000^{2i/d_{model}}) PE(pos,2i+1)=cos(pos/100002i/dmodel)
PE的代码:

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)
        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)
        pe = pe.unsqueeze(0)
        self.register_buffer('pe', pe)
        
    def forward(self, x):
        x = x + Variable(self.pe[:, :x.size(1)], 
                         requires_grad=False)
        return self.dropout(x)

上述代码的计算流程图:
[NLP]——The Annotated Transformer(模型篇)_第3张图片
PE的好处:

  • 绝对位置(absolute position):根据上述公式,不同的postion,每一个维度的值都不同,体现了绝对位置信息
  • 相对位置(relative position):使用sin和cos的好处是,不同位置之间可以通过简单的加减来进行转换。比如pos和pos+k:
    由于:
    s i n ( α + β ) = s i n ( α ) c o s ( β ) + s i n ( β ) c o s ( α ) sin(α+β)=sin(α)cos(β)+sin(β)cos(α) sin(α+β)=sin(α)cos(β)+sin(β)cos(α)
    c o s ( α + β ) = c o s ( α ) c o s ( β ) − s i n ( α ) s i n ( β ) cos(α+β)=cos(α)cos(β)-sin(α)sin(β) cos(α+β)=cos(α)cos(β)sin(α)sin(β)
    所以:
    P E ( p o s + k , 2 i ) = P E ( p o s , 2 i ) P E ( k , 2 i + 1 ) + P E ( k , 2 i ) P E ( p o s , 2 i + 1 ) PE(pos+k,2i)=PE(pos,2i)PE(k,2i+1)+PE(k,2i)PE(pos,2i+1) PE(pos+k,2i)=PE(pos,2i)PE(k,2i+1)+PE(k,2i)PE(pos,2i+1)
    P E ( p o s + k , 2 i + 1 ) = P E ( p o s , 2 i + 1 ) P E ( k , 2 i + 1 ) − P E ( p o s , 2 i ) P E ( k , 2 i ) PE(pos+k,2i+1)=PE(pos,2i+1)PE(k,2i+1)-PE(pos,2i)PE(k,2i) PE(pos+k,2i+1)=PE(pos,2i+1)PE(k,2i+1)PE(pos,2i)PE(k,2i)

同一个维度(dim)在不同的位置(pos)上的值,构成正弦曲线:

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]])
None

[NLP]——The Annotated Transformer(模型篇)_第4张图片
另外,positional embeddings也可以是和token embeddings一样的、可学习的参数矩阵,一方面,两者的结果差不多;另一方面,正弦版本的PE允许模型外推到比训练中遇到的序列长度更长的情况,所以选择正弦版本的。(We chose the sinusoidal version because it may allow the model to extraopolate to sequence lengths longer than the ones encountered during training)

完整模型

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
tmp_model = make_model(10, 10, 2)

实战

to be continued

参考

http://nlp.seas.harvard.edu/2018/04/03/attention.html

你可能感兴趣的:(nlp之家)