赞
踩
由encoder + decoder组成。
6个相同的encoder, dmodel=512 , 前向网络d_ff=2048
多头h=8, dropout=0.1
decoder后面其实还有一个linear+softmax 步骤操作
对应的整体结构和代码如下所示:
目前大部分比较热门的神经序列转换模型都有Encoder-Decoder结构[9]。Encoder将输入序列 (x1,x2,xn)映射到一个连续表示序列(z1,z2,zn)。
对于编码得到的z,Decoder每次解码生成一个符号,直到生成完整的输出序列:(y1, y2, ym)。对于每一步解码,模型都是自回归的,即在生成下一个符号时将先前生成的符号作为附加输入。
class EncoderDecoder(nn.Module): """ A standard Encoder-Decoder architecture. Base for this and many other models. """ def __init__(self, encoder, decoder, src_embed, tgt_embed, generator): super(EncoderDecoder, self).__init__() self.encoder = encoder self.decoder = decoder self.src_embed = src_embed self.tgt_embed = tgt_embed self.generator = generator 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." # 最后的linear + softmax步骤,如下所示 def __init__(self, d_model, vocab): super(Generator, self).__init__() self.proj = nn.Linear(d_model, vocab) def forward(self, x): return F.log_softmax(self.proj(x), dim=-1)
注意:每次与decoder交互的只有最后一层encoder层
由6层相同的encoder层组成, d维度为512
# encoder层,包括自注意力和前向add 和 norm. 以及残差连接 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 # 前向add 和 norm self.sublayer = clones(SublayerConnection(size, dropout), 2) # 残差连接 self.size = size def forward(self, x, mask): "Follow Figure 1 (left) for connections." # 两个残差连接,第一个是attention , 第二个是前向 x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward) # 前向残差连接层 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))) #整个encoder 结构:6层encoderlayer + norm 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) # 复制n层 def clones(module, N): "Produce N identical layers." return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) # LN归一化层 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
只有encoder 最后一层layer交互
masked self att + atttion + feedforward + 残差
# decoder层:masked self att + atttion + feedforward + 残差 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)) # 注意这里的mask x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask)) return self.sublayer[2](x, self.feed_forward) 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) 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
Q,K,V为什么scale
8个头
Transformer中以三种不同的方式使用了“多头”Attention:
- 在"Encoder-Decoder Attention"层,Query来自先前的解码器层,并且Key和Value来自Encoder的输出。Decoder中的每个位置Attend输入序列中的所有位置,这与Seq2Seq模型中的经典的Encoder-Decoder Attention机制[15]一致。
- Encoder中的Self-attention层。在Self-attention层中,所有的Key、Value和Query都来同一个地方,这里都是来自Encoder中前一层的输出。Encoder中当前层的每个位置都能Attend到前一层的所有位置。
- 类似的,解码器中的Self-attention层允许解码器中的每个位置Attend当前解码位置和它前面的所有位置。这里需要屏蔽解码器中向左的信息流以保持自回归属性。具体的实现方式是在缩放后的点积Attention中,屏蔽(设为负无穷)Softmax的输入中所有对应着非法连接的Value。
def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) \ / math.sqrt(d_k) 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 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_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)
Feed Forward NetWork 翻译成中文叫 前馈网络,其实就是MLP。我们这里不纠结于FFN的定义,我们直接看下transformer里是怎么实现的
dmodle = 512, 即4 * dmodle,为2048,因此,W1,W2大小为512 * 2048,2个为 2 * 512 * 2048。
Q,K,V向量的维数小于embedding的维数。它们的维数为64,而 embedding 和 encoder input/output 的维数为512。这是为了后面的multiheaded attention 计算方便选择的
Bert沿用了惯用的全连接层大小设置,即4 * dmodle,为3072,因此,W1,W2大小为768 * 3072,2个为 2 * 768 * 3072。
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))))
encoder的embedding, docoder的embedding,共享同样的embedding
乘以维度的二次根
Transformer采用的是随机初始化,然后训练的方式。词向量维度为[vocab_size, d_model]
class Embeddings(nn.Module):
#d_model=512, vocab=当前语言的词表大小
def __init__(self, d_model, vocab):
super(Embeddings, self).__init__()
# one-hot转词嵌入,这里有一个待训练的矩阵E,大小是vocab*d_model
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)
# 得到的n*512词嵌入矩阵,主动乘以sqrt(512)=22.6,
#这里我做了一些对比,感觉这个乘以sqrt(512)没啥用… 求反驳。
#这里的输出的tensor大小类似于(batch.size, sequence.length, 512)
注意,位置编码不会更新,是写死的,所以这个class里面没有可训练的参数。
PE模块的主要做用是把位置信息加入到输入向量中,使模型知道每个字的位置信息。对于每个位置的P E是固定的,不会因为输入的句子不同而不同,且每个位置的P E大小为1 ∗ n (n为word embedding 的dim size),transformer中使用正余弦波来计算P E,具体如下:
为什么选择这个函数作为位置函数
1.我们之所以选择这个函数,是因为我们假设它可以让模型很容易地通过相对位置来学习,因为对任意确定的偏移k, PE_{pos+k}可以表示为PE_{pos}的线性函数。
2.我们还尝试使用预先学习的positional embeddings 来代替正弦波,发现这两个版本产生了几乎相同的结果 。我们之所以选择正弦曲线,是因为它允许模型扩展到比训练中遇到的序列长度更长的序列。
3.但是PEt PE t+k 的度量只与k的大小有关,与谁在前,谁在后无关。即,经过dot-attention机制后,我们把positional embedding中的顺序信息丢失了。所以,从这方面看,正弦波这种位置PE并不太适合在用在transformer结构中,这也可能是后面的bert,t5都采用的基于学习的positional embedding。(注:模块3Add会把顺序信息传递下去,但我们还是在算法的核心处理上丢失了信息。)
class PositionalEncoding(nn.Module): "Implement the PE function." #d_model=512,dropout=0.1, #max_len=5000代表事先准备好长度为5000的序列的位置编码,其实没必要, #一般100或者200足够了 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. #(5000,512)矩阵,保持每个位置的位置编码,一共5000个位置, #每个位置用一个512维度向量来表示其位置编码 pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len).unsqueeze(1) # (0,2,…, 4998)一共准备2500个值,供sin, cos调用 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)
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。