Transformer 大语言模型(LLM)基石 - Transformer架构详解 - 解码器(Decoder)详解以及算法实现

锋哥原创的Transformer 大语言模型(LLM)基石视频教程:

https://www.bilibili.com/video/BV1X92pBqEhV

课程介绍

本课程主要讲解Transformer简介,Transformer架构介绍,Transformer架构详解,包括输入层,位置编码,多头注意力机制,前馈神经网络,编码器层,解码器层,输出层,以及Transformer Pytorch2内置实现,Transformer基于PyTorch2手写实现等知识。

Transformer 大语言模型(LLM)基石 - Transformer架构详解 - 解码器(Decoder)详解以及算法实现

Transformer 解码器是 Transformer 模型的重要组成部分,主要用于生成序列,提取特征。

核心特点:

  1. 自注意力机制(Self-Attention):允许解码器关注输入序列的不同部分,但在解码器中,为了防止信息泄露,通常使用掩码自注意力(masked self-attention),确保当前位置只能关注之前的位置。

  2. 编码器-解码器注意力机制(Encoder-Decoder Attention):允许解码器关注编码器的输出。

  3. 前馈神经网络(Feed-Forward Network):每个注意力层后都有一个前馈网络。

解码器层通常由以下子层组成: a. 掩码自注意力层(Masked Multi-Head Self-Attention) b. 编码器-解码器注意力层(Multi-Head Cross-Attention) c. 前馈神经网络层(Feed-Forward Network)

每个子层后面都有残差连接(Residual Connection)和层归一化(Layer Normalization)。

代码实现:

复制代码
# 解码器层
class DecoderLayer(nn.Module):

    def __init__(self, d_model, self_attention, cross_attention, d_ff, dropout=0.1):
        super().__init__()
        self.d_model = d_model  # 词嵌入维度大小
        self.self_attention = self_attention  # 多头自注意力机制
        self.cross_attention = cross_attention  # 多头交叉注意力机制
        self.feed_forward = d_ff  # 前馈神经网络
        self.residual_connection1 = ResidualConnection(d_model, dropout)  # 残差连接
        self.residual_connection2 = ResidualConnection(d_model, dropout)  # 残差连接
        self.residual_connection3 = ResidualConnection(d_model, dropout)  # 残差连接

    def forward(self, x, encoder_output, mask):
        """
        前向传播
        :param x: 解码器输入
        :param encoder_output: 编码器输出结果 [3,5,512]
        :param mask: 掩码
        :return:
        """
        # 多头自注意力机制
        x1 = self.residual_connection1(x, lambda x: self.self_attention(x, x, x, mask))
        # 多头交叉注意力机制
        x2 = self.residual_connection2(x1, lambda x: self.cross_attention(x, encoder_output, encoder_output))
        # 前馈神经网络
        x3 = self.residual_connection3(x2, lambda x: self.feed_forward(x))
        return x3


# 解码器(由多个解码器层堆叠)
class Decoder(nn.Module):

    def __init__(self, num_layers, layer):
        super().__init__()
        self.layers = nn.ModuleList([copy.deepcopy(layer) for _ in range(num_layers)])
        self.norm = LayerNorm(layer.d_model)

    def forward(self, x, encoder_output, mask):
        """
        前向传播
        :param x: 解码器输入
        :param encoder_output: 编码器的输出结果 [3,5,512]
        :param mask: 掩码
        :return:
        """
        for layer in self.layers:
            x = layer(x, encoder_output, mask)
        return self.norm(x)


# 测试解码器
def test_decoder():
    vocab_size = 2000  # 词表大小
    embedding_dim = 512  # 词嵌入维度大小
    embeddings = Embeddings(vocab_size, embedding_dim)
    embed_result = embeddings(torch.tensor([[23, 5, 77, 3, 55], [166, 12, 13, 122, 15], [166, 21, 13, 14, 15]]))
    positional_encoding = PositionalEncoding(embedding_dim)
    positional_result = positional_encoding(embed_result)
    mha = MultiHeadAttention(d_model=512, num_heads=8)  # 多头自注意力机制
    ffn = FeedForward(d_model=512, d_ff=2048)  # 前馈神经网络
    # 实例化解码器对象
    decoder_layer = DecoderLayer(d_model=512, self_attention=mha, cross_attention=mha, d_ff=ffn)
    # 编码器输入
    encoder_output = test_encoder()
    mask = create_sequence_mask(5)
    # 实例化解码器对象
    decoder = Decoder(num_layers=6, layer=decoder_layer)
    decoder_result = decoder(positional_result, encoder_output, mask)
    print('decoder_result.shape:', decoder_result.shape)


if __name__ == '__main__':
    # test_encoder()
    test_decoder()

运行输出:

相关推荐
江畔柳前堤4 小时前
大语言模型分布式训练:从并行策略到万卡工程的系统梳理
人工智能·分布式·深度学习·算法·目标检测·机器学习·语言模型
AI创界者5 小时前
MiniMax-H3 本地一键部署整合包:8G 显存玩转文图生视频、视频参考、角色替换与超分补帧全流程
人工智能·深度学习
江畔柳前堤5 小时前
HBM:大语言模型时代的「算力血液」——从内存墙到带宽革命的深度拆解
服务器·人工智能·windows·目标检测·语言模型·自然语言处理·软件工程
JouYY7 小时前
大模型底层学习(三)-从零训练一个 BPE 分词器
架构·llm·agent
论文避坑指南7 小时前
论文写作全流程AI合规边界:从选题到投稿的“红绿灯“清单
大数据·人工智能·深度学习
蛋先生DX8 小时前
大模型参数存储格式揭秘:BF不是男朋友
深度学习·算法·llm
杀生丸学AI8 小时前
【前馈三维重建】SAF3R:前馈式3D重建Transformer的动态稀疏注意力(加速)
深度学习·3d·transformer
大模型码小白13 小时前
【AI】一文讲清 RAG:从大模型局限到企业级知识库落地流程
人工智能·深度学习·学习
鬼手点金14 小时前
与LLM结合的主流智能爬虫框架
爬虫·python·llm·post·request·firecrawl·crawl4ai