编码器-解码器 Transformer

使用 PyTorch 的 Transformer 模型

James Chapman

Curriculum Manager, DataCamp

编码器遇上解码器

原始 Transformer 架构

使用 PyTorch 的 Transformer 模型

编码器遇上解码器

编码器与解码器组合

使用 PyTorch 的 Transformer 模型

交叉注意力机制

 

  1. 信息在解码器中逐步处理
  2. 来自编码器块的最终隐藏状态

 

交叉注意力示例

带交叉注意力的解码器

使用 PyTorch 的 Transformer 模型

修改 DecoderLayer

 

  1. 信息在解码器中逐步处理
  2. 来自编码器块的最终隐藏状态

 

  • x解码器信息流,作为交叉注意力的查询
  • y编码器输出,作为交叉注意力的
class DecoderLayer(nn.Module):
    def __init__(self, d_model, num_heads, d_ff, dropout):
        super().__init__()
        self.self_attn = MultiHeadAttention(
                          d_model, num_heads)
        self.cross_attn = MultiHeadAttention(
                          d_model, num_heads)
        ...


def forward(self, x, y, tgt_mask, cross_mask): self_attn_output = self.self_attn(x, x, x, tgt_mask) x = self.norm1(x + self.dropout(self_attn_output)) cross_attn_output = self.cross_attn(x, y, y, cross_mask) x = self.norm2(x + self.dropout(cross_attn_output)) ...
使用 PyTorch 的 Transformer 模型

修改 DecoderTransformer

 

仅解码器
class TransformerDecoder(nn.Module):
...
def forward(self, x, tgt_mask):
    x = self.embedding(x)
    x = self.positional_encoding(x)
    for layer in self.layers:
        x = layer(x, tgt_mask)
    x = self.fc(x)
    return F.log_softmax(x, dim=-1)

 

编码器-解码器
class TransformerDecoder(nn.Module):
...

def forward(self, x, y, tgt_mask, cross_mask): x = self.embedding(x) x = self.positional_encoding(x) for layer in self.layers: x = layer(x, y, tgt_mask, cross_mask) x = self.fc(x) return F.log_softmax(x, dim=-1)
使用 PyTorch 的 Transformer 模型

编码器遇上解码器

编码器与解码器组合

使用 PyTorch 的 Transformer 模型

Transformer 头

 

翻译输出示例

  • jugar("玩"):0.03
  • viajar("旅行"):0.96
  • dormir("睡觉"):0.01

其他任务可能需要不同的激活函数

带分类头的解码器

使用 PyTorch 的 Transformer 模型

整合在一起!

整体编码器-解码器 Transformer

使用 PyTorch 的 Transformer 模型

整合在一起!

class InputEmbeddings(nn.Module):
  ...  
class PositionalEncoding(nn.Module):
  ...  
class MultiHeadAttention(nn.Module):
  ...
class FeedForwardSubLayer(nn.Module):
  ...  
class EncoderLayer(nn.Module):
  ...
class DecoderLayer(nn.Module):
  ...
class TransformerEncoder(nn.Module):
  ...
class TransformerDecoder(nn.Module):
  ...
class ClassificationHead(nn.Module):
  ...
class Transformer(nn.Module):
    def __init__(self, vocab_size, d_model, num_heads, 
                 num_layers, d_ff, max_seq_len, dropout):
        super().__init__()


self.encoder = TransformerEncoder(vocab_size, d_model, num_heads, num_layers, d_ff, dropout, max_seq_len) self.decoder = TransformerDecoder(vocab_size, d_model, num_heads, num_layers, d_ff, dropout, max_seq_len)
def forward(self, x, src_mask, tgt_mask, cross_mask): encoder_output = self.encoder(x, src_mask) decoder_output = self.decoder(x, encoder_output, tgt_mask, cross_mask) return decoder_output
使用 PyTorch 的 Transformer 模型

Passons à la pratique !

使用 PyTorch 的 Transformer 模型

Preparing Video For Download...