第八章 Transformer代码详解

系列文章目录

第一章 机器学习技术分类

第二章 深度学习基础——层和函数

第三章 卷积神经网络模型的发展

第四章 ResNet

第五章 MobileNet

第六章 深度学习中的注意力机制

第七章 Transformer概述

第八章 Transformer代码详解


文章目录

系列文章目录

 一、Transformer初始化和forward参数详解

2.Forward参数

2.1 [src/tgt/memory]_mask

二、Transformer

1.编码器模块

1.1 Self-Attention Layer

1.2 Feed Forward Neural Network

2.解码器模块

​​​​​​​2.1 Self-Attention Layer

​​​​​​​2.2 Encoder-Decoder Attention Layer

​​​​​​​2.3 Feed Forward Neural Network

参考文献


 一、Transformer初始化和forward参数详解

1.初始化参数

Transformer — PyTorch 2.4 documentation

  • d_model (int) – the number of expected features in the encoder/decoder inputs (default=512). 输入的特征维度,也就是每个单词经过Input Embedding和Positional Encoding后的向量维度。
  • nhead (int) – the number of heads in the multiheadattention models (default=8).多头注意力的头数。
  • num_encoder_layers (int) – the number of sub-encoder-layers in the encoder (default=6). 编码器中连续堆叠的编码模块的数目。
  • num_decoder_layers (int) – the number of sub-decoder-layers in the decoder (default=6). 解码器中连续堆叠的解码器模块的数目。
  • dim_feedforward (int) – the dimension of the feedforward network model (default=2048). 编/解码器中的前馈神经网络的维度
  • dropout (float) – the dropout value (default=0.1). dropout参数,用于self-attention和feedforward的输出。
  • activation (Union[strCallable[[Tensor], Tensor]]) – the activation function of encoder/decoder intermediate layer, can be a string (“relu” or “gelu”) or a unary callable. Default: relu 激活函数,用于feedforward第一层全连接之后
  • custom_encoder (Optional[Any]) – custom encoder (default=None). 自定义编码器
  • custom_decoder (Optional[Any]) – custom decoder (default=None). 自定义解码器
  • layer_norm_eps (float) – the eps value in layer normalization components (default=1e-5). 归一化层的参数,自注意力和feedforward各有一个归一化层
  • batch_first (bool) – If True, then the input and output tensors are provided as (batch, seq, feature). Default: False (seq, batch, feature). 如果设置为True,则输入和输出tensor的shape为(batch, seq, feature);如果设置为false,则输入和输出tensor的shape为(seq, batch, feature);
  • norm_first (bool) – if True, encoder and decoder layers will perform LayerNorms before other attention and feedforward operations, otherwise after. Default: False (after). 如果设置为True,则对自注意力和feedforward的输入做归一化;如果设置为false,则对自注意力和feedforward的输出做归一化
  • bias (bool) – If set to False, Linear and LayerNorm layers will not learn an additive bias. Default: True 如果设置为False,则自注意力的KV的全连接映射无bias,feedforward的两层全连接无bias,自注意力和feedforward中的归一化层无bias

        初始化参数的前五个是最重要的参数,影响Transformer的模型结构。后面的参数(除custom_encodercustom_decoder)都是对自注意力和feedforward的局部设置。

2.Forward参数

  • src (Tensor) – the sequence to the encoder (required). 编码器的输入序列。如果初始化函数batch_first = False,shape为(S, N, E);batch_first = True,shape为(N, S, E)。Shape也可以是(S, E)。

        multi_head_attention_forward计算之前会统一转换为(S, N, E)。

        如果Shape是(S, E),那么在multi_head_attention_forward中第一步就是在dim=1添加batch=1;

  • tgt (Tensor) – the sequence to the decoder (required). 解码器的输入序列(T, N, E),和src类似。
  • src_mask (Optional[Tensor]) – the additive mask for the src sequence (optional). 对src序列进行附加掩码。不常用。形状为(S, S)或者(N*num_heads ,S , S)
  • tgt_mask (Optional[Tensor]) – the additive mask for the tgt sequence (optional). 对tgt序列进行附加掩码。常用。形状为(T, T)或者(N*num_heads ,T, T)
  • memory_mask (Optional[Tensor]) – the additive mask for the encoder output (optional). 对编码器输出进行附加掩码。不常用。形状为(T, S)。
  • src_key_padding_mask (Optional[Tensor]) – the Tensor mask for src keys per batch (optional). 逐通道对src key进行附加掩码。常用。形状为(S)或者(N, S)。
  • tgt_key_padding_mask (Optional[Tensor]) – the Tensor mask for tgt keys per batch (optional). 逐通道对tgt key进行附加掩码。常用。形状为(T)或者(N, T)。
  • memory_key_padding_mask (Optional[Tensor]) – the Tensor mask for memory keys per batch (optional). 逐通道对memory key进行附加掩码。不常用。形状为(S)或者(N, S)。
  • src_is_causal (Optional[bool]) – If specified, applies a causal mask as src_mask. Default: None; try to detect a causal mask. Warning: src_is_causal provides a hint that src_mask is the causal mask. Providing incorrect hints can result in incorrect execution, including forward and backward compatibility.
  • tgt_is_causal (Optional[bool]) – If specified, applies a causal mask as tgt_mask. Default: None; try to detect a causal mask. Warning: tgt_is_causal provides a hint that tgt_mask is the causal mask. Providing incorrect hints can result in incorrect execution, including forward and backward compatibility.
  • memory_is_causal (bool) – If specified, applies a causal mask as memory_mask. Default: False. Warning: memory_is_causal provides a hint that memory_mask is the causal mask. Providing incorrect hints can result in incorrect execution, including forward and backward compatibility.
  • 输出:Tensor。如果初始化函数batch_first = False,shape为(T, N, E);batch_first = True,shape为(N, T, E)。Shape也可以是(T, E)。解码器的输入和输出的序列长度相同。

        [src/tgt/memory]_mask:用于在计算注意力权重时屏蔽某些位置未来的位置或指定位置),防止信息泄露或特定位置的信息影响计算。如果提供的是 BoolTensor,则值为 True 的位置不被允许参与注意力计算;而值为 False 的位置将保持不变。如果提供的是 FloatTensor,它将被添加到注意权重中。

        [src/tgt/memory]_key_padding_mask 用于在计算注意力权重时忽略某些填充位置(padding),确保这些填充值不会影响模型的注意力计算。如果提供的是 BoolTensor,则值为 True 的位置将被忽略,而值为 False 的位置将保持不变。

        [src/tgt/memory]_mask加上[src/tgt/memory]_key_padding_mask就是MultiheadAttention中的atten_mask。

        2.1 [src/tgt/memory]_mask

        在Transformer推理的过程中,第i次调用时解码器的输入为tgt的前i个token,那么在计算自注意力时仅有前i个token参与。在训练的过程中,tgt输入的第i个token在计算注意力时,仅应该选择tgt的前i个token参与计算,第i个token之后的其他tokens不应该参与计算(等效于推理过程中仅知道历史输入,需要屏蔽未来信息)。这个就是通过tgt_mask实现的,可以通过nn.Transformer.generate_square_subsequent_mask生成tgt_mask。tgt_mask的对角线和下三角元素为0,上三角元素为-inf。(-inf在softmax后的权重为0)

        2.2 [src/tgt/memory]_key_padding_mask

在src和tgt对应的原始tokens序列中,包含了三种特殊token:起始 <bos>0,终止 <eos>1 和扩充 <pad>2。这里面的<pad>只是为了将序列扩充到特定长度,从而将不同长度的序列组成batch。该token没有任何意义,所以不应该参与Attention计算。<pad>位置的遮掩是通过key_padding_mask实现的,可以通过nn.functional.pad生成;或者使用如下代码生成

        如下图所示,P表示Padding的位置,右边的矩阵表示计算得到的注意力权重矩阵。可以看到,此时的注意力权重对于Padding位置上的信息也会加以考虑。因此在Transformer中,作者通过在生成训练集的过程中记录下每个样本Padding的实际位置;然后再将注意力权重矩阵中对应位置的权重替换成负无穷便达到了忽略Padding位置信息的目的(看起来好像是把K矩阵中对应的行修改为-inf)。这种做法也是Encoder-Decoder网络结构中通用的一种办法。

二、Transformer

        编码器中多个编码器模块串联,上一个编码器模块的输出就是下一个编码器模块的输入。最后一个编码器模块的输出就是编码器的输出,并没有保存所有编码器模块的输出。

        编码器的输出作为解码器多个模块的Encoder-Decoder Attention Layer的query和key。解码器中多个解码器模块也是串联,上一个解码器模块的输出就是下一个解码器模块Self-Attention Layer的输入。

        解码器的输出就是Transformer的输出(仅针对PyTorch中的nn.Transformer)。

1.编码器模块

        单个编码器模块主要由两部分组成:

  • Self-Attention Layer
  • Feed Forward Neural Network(前馈神经网络,缩写为 FFNN)

        不论是Self-Attention Layer还是Feed Forward Neural Network都仅建模残差。

        1.1 Self-Attention Layer

        MultiheadAttention的forward函数调用的是nn.functional.multi_head_attention_forward。

  • in-projection

        多头注意力的每一个头首先使用全连接层将查询、键和值变换到另一个空间。如此每个头中Scaled Dot-product Attention的输入互不相同,才能使得不同的头关注不同方面的语义相似性。

  •  prep attention mask

        初始attention mask就是[src/tgt/memory]_mask,用于在计算注意力权重时屏蔽某些位置(未来的位置或指定位置),防止信息泄露或特定位置的信息影响计算。在编码器中,仅src_mask启用,形状为(S, S)或者(N*num_heads ,S , S)。一般情况下,src_mask为None。

        prep attention mask仅在src_mask不为None时,检查src_mask的shape,扩充batch。

  • add bias along batch dimension (currently second)

        MultiheadAttention的类定义中有bias_k和bias_v两个Tensor,除非改动源码,通常为None。此代码段不生效。

  • reshape q, k, v for multihead attention and make em batch first

  • add zero attention along batch dimension (now first)

        添加全0 batch。

  • merge key padding and attention masks

​​​​​​​

  • calculate attention and out projection

        need_weight可以确定是否输出注意力权重,编码器中的need_weight设置为False。

        此步骤为MultiheadAttention除in-projection之外的实际计算部分。最后一层为ExE

全连接。

  • scaled_dot_product_attention

​​​​​​​        1.2 Feed Forward Neural Network

        两层全连接网络,第一层全连接将特征数从d_model扩充到dim_feedforward,第二层全连接将特征数从dim_feedforward缩减到d_model。

​​​​​​​2.解码器模块

        单个解码器模块主要由三部分组成:

  • Self-Attention Layer
  • Encoder-Decoder Attention Layer:帮助解码器聚焦于输入序列最相关的部分(类似于seq2seq模型中的 Attention)
  • Feed Forward Neural Network(前馈神经网络,缩写为 FFNN)

        ​​​​​​​2.1 Self-Attention Layer

        解码器的Self-Attention Layer和编码器的Self-Attention Layer结构上完全一致,区别是解码器的Self-Attention Layer输入的tgt_mask一般不为空。

​​​​​​​        2.2 Encoder-Decoder Attention Layer

        ​​​​​​​2.3 Feed Forward Neural Network

        两层全连接,和编码器模块中的Feed Forward Neural Network一致。

参考文献

Transformer各层网络结构详解!面试必备!(附代码实现) - mantch - 博客园

第二章:Transformer 模型 · Transformers快速入门

Transformer入门(1):模型简介及其在机器视觉上的应用 - 陶小桃Blog

learn-nlp-with-transformers/docs at main · datawhalechina/learn-nlp-with-transformers · GitHub

10.5. 多头注意力 — 动手学深度学习 2.0.0 documentation

Pytorch中 nn.Transformer的使用详解与Transformer的黑盒讲解-CSDN博客

https://www.zhihu.com/question/455164736/answer/2249656196

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值