【实践】Pytorch nn.Transformer的mask理解-程序员宅基地

技术标签: 算法  python  深度学习  人工智能  自然语言处理  

点击上方,选择星标,每天给你送干货!


仅作学术分享,不代表本公众号立场,侵权联系删除

知乎丨林小平

来源丨https://zhuanlan.zhihu.com/p/353365423

编辑丨极市平台

pytorch也自己实现了transformer的模型,不同于huggingface或者其他地方,pytorch的mask参数要更难理解一些(即便是有文档的情况下),这里做一些补充和说明。(顺带提一句,这里的transformer是需要自己实现position embedding的,别乐呵乐呵的就直接去跑数据了)

>>> transformer_model = nn.Transformer(nhead=16, num_encoder_layers=12)
>>> src = torch.rand((10, 32, 512))
>>> tgt = torch.rand((20, 32, 512))
>>> out = transformer_model(src, tgt) # 没有实现position embedding ,也需要自己实现mask机制。否则不是你想象的transformer

首先看一下官网的参数

  • src – the sequence to the encoder (required).

  • tgt – the sequence to the decoder (required).

  • src_mask – the additive mask for the src sequence (optional).

  • tgt_mask – the additive mask for the tgt sequence (optional).

  • memory_mask – the additive mask for the encoder output (optional).

  • src_key_padding_mask – the ByteTensor mask for src keys per batch (optional).

  • tgt_key_padding_mask – the ByteTensor mask for tgt keys per batch (optional).

  • memory_key_padding_mask – the ByteTensor mask for memory keys per batch (optional).

这里面最大的区别就是*mask_和*_key_padding_mask,_至于*是src还是tgt,memory,这不重要,模块出现在encoder,就是src,出现在decoder,就是tgt,decoder每个block的第二层和encoder做cross attention的时候,就是memory。

*mask 对应的API是attn_mask*_key_padding_mask对应的API是key_padding_mask

我们看看torch/nn/modules/activation.py当中MultiheadAttention模块对于这2个API的解释:

def forward(self, query, key, value, key_padding_mask=None,                need_weights=True, attn_mask=None):        # type: (Tensor, Tensor, Tensor, Optional[Tensor], bool, Optional[Tensor]) -> Tuple[Tensor, Optional[Tensor]]        r"""    Args:        query, key, value: map a query and a set of key-value pairs to an output.            See "Attention Is All You Need" for more details.        key_padding_mask: if provided, specified padding elements in the key will            be ignored by the attention. When given a binary mask and a value is True,            the corresponding value on the attention layer will be ignored. When given            a byte mask and a value is non-zero, the corresponding value on the attention            layer will be ignored        need_weights: output attn_output_weights.        attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all            the batches while a 3D mask allows to specify a different mask for the entries of each batch.    Shape:        - Inputs:        - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is          the embedding dimension.        - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is          the embedding dimension.        - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is          the embedding dimension.        - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.          If a ByteTensor is provided, the non-zero positions will be ignored while the position          with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the          value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.        - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.          3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,          S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked          positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend          while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True``          is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor          is provided, it will be added to the attention weight.
        - Outputs:        - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,          E is the embedding dimension.        - attn_output_weights: :math:`(N, L, S)` where N is the batch size,          L is the target sequence length, S is the source sequence length.        """

  • key_padding_mask:用来遮蔽<PAD>以避免pad token的embedding输入。形状要求:(N,S)

  • attn_mask:2维或者3维的矩阵。用来避免指定位置的embedding输入。2维矩阵形状要求:(L, S);也支持3维矩阵输入,形状要求:(N*num_heads, L, S)

其中,N是batch size的大小,L是目标序列的长度(the target sequence length),S是源序列的长度(the source sequence length)。这个模块会出现在上图的3个橙色区域,所以the target sequence 并不一定就是指decoder输入的序列,the source sequence 也不一定就是encoder输入的序列。

更准确的理解是,target sequence代表多头attention当中q(查询)的序列,source sequence代表k(键值)和v(值)的序列。例如,当decoder在做self-attention的时候,target sequence和source sequence都是它本身,所以此时L=S,都是decoder编码的序列长度。

key_padding_mask的作用

这里举一个简单的例子:

现在有一个batch,batch_size = 3,长度为4,token表现形式如下:

[    [‘a’,'b','c','<PAD>'],    [‘a’,'b','c','d'],    [‘a’,'b','<PAD>','<PAD>']]

现在假设你要对其进行self-attention的计算(可以在encoder,也可以在decoder),那么以第三行数据为例,‘a’在做qkv计算的时候,会看到'b','<PAD>','<PAD>',但是我们不希望‘a’看到'<PAD>',因为他们本身毫无意义,所以,需要key_padding_mask遮住他们。

key_padding_mask的形状大小为(N,S),对应这个例子,key_padding_mask为以下形式,key_padding_mask.shape = (3,4):

[    [False, False, False, True],    [False, False, False, False],    [False, False, True, True]]

值得说明的是,key_padding_mask本质上是遮住key这个位置的值(置0),但是<PAD> token本身,也是会做qkv的计算的,以第三行数据的第三个位置为例,它的q是<PAD>的embedding,k和v分别各是第一个的‘a’和第二个的‘b’,它也会输出一个embedding。

所以你的模型训练在transformer最后的output计算loss的时候,还需要指定ignoreindex=pad_index。以第三行数据为例,它的监督信号是[3205,1890,0,0],pad_index=0 。如此一来,即便位于<PAD>的transformer会疯狂的和有意义的position做qkv,也会输出embedding,但是我们不算它的loss,任凭它各种作妖。

attn_mask的作用

一开始看到有2个mask参数的时候,我也是一脸懵逼的,并且他们的shape居然要求还不一样。attn_mask到底用在什么地方呢?

decoder在做self-attention的时候,每一个位置不同于encoder,他是只能看到上文的信息的。key_padding_mask的shape为(batch_size, source_length),这意味着每个位置的query,他所看到的画面经过key_padding_mask后都是一样的(尽管他能做到batch的每一行数据mask的不一样),这不能满足如下模块的需求:

decoder的mask 多头注意力模块

这里需要的mask如下:

黄色是看得到的部分,紫色是看不到的部分,不同位置需要mask的部分是不一样的

而pytorch的nn.Transformer已经有了帮我们实现的函数:

    def generate_square_subsequent_mask(self, sz: int) -> Tensor:        r"""Generate a square mask for the sequence. The masked positions are filled with float('-inf').            Unmasked positions are filled with float(0.0).        """        mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)        mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))        return mask

还是上面那个例子,以第一行数据['a','b','c','<PAD>'],为例(假设我们在用decoder做生成,研究block 的第一层layer 也就是self-attention),此时:

  • 'a'可以看到'a'

  • 'b'可以看到'a','b'

  • 'c'可以看到'a','b','c'

  • '<PAD>'理论上不应该看到什么,但是只要它头顶的监督信号是ignore_index,那就没有关系,所以让他看到'a','b','c','<PAD>'

回想一下attn_mask的形状要求,2维的时候是(L,S),3维的时候是(N*num_heads, L, S)。此时,由于qkv都是同一个序列(decoder底下的序列)所以L=S;又因为对于batch每一行数据来说,他们的mask机制都是一样的,即第i个位置的值,都只能看到上文的信息,所以我们的attn_mask用二维的就行,内部实现的时候会把mask矩阵广播到batch每一行数据中:

一般而言,除非你需要魔改transformer,例如让不同的头看不同的信息,否则二维的矩阵足够使用了。

什么时候用key_padding_mask,什么时候用attn_mask?

个人感觉最好是按照上面的约定的习惯来用,实际上,2个mask共同作用于同一个模型,非要用attn_mask代替key_padding_mask把<PAD>遮住,行不行?当然可以,只不过这只会增加你的工作量。

说个正事哈

由于微信平台算法改版,公号内容将不再以时间排序展示,如果大家想第一时间看到我们的推送,强烈建议星标我们和给我们多点点【在看】。星标具体步骤为:

(1)点击页面最上方深度学习自然语言处理”,进入公众号主页。

(2)点击右上角的小点点,在弹出页面点击“设为星标”,就可以啦。

感谢支持,比心

投稿或交流学习,备注:昵称-学校(公司)-方向,进入DL&NLP交流群。

方向有很多:机器学习、深度学习,python,情感分析、意见挖掘、句法分析、机器翻译、人机对话、知识图谱、语音识别等。

记得备注呦

整理不易,还望给个在看!
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_27590277/article/details/115436108

智能推荐

Docker 快速上手学习入门教程_docker菜鸟教程-程序员宅基地

文章浏览阅读2.5w次,点赞6次,收藏50次。官方解释是,docker 容器是机器上的沙盒进程,它与主机上的所有其他进程隔离。所以容器只是操作系统中被隔离开来的一个进程,所谓的容器化,其实也只是对操作系统进行欺骗的一种语法糖。_docker菜鸟教程

电脑技巧:Windows系统原版纯净软件必备的两个网站_msdn我告诉你-程序员宅基地

文章浏览阅读5.7k次,点赞3次,收藏14次。该如何避免的,今天小编给大家推荐两个下载Windows系统官方软件的资源网站,可以杜绝软件捆绑等行为。该站提供了丰富的Windows官方技术资源,比较重要的有MSDN技术资源文档库、官方工具和资源、应用程序、开发人员工具(Visual Studio 、SQLServer等等)、系统镜像、设计人员工具等。总的来说,这两个都是非常优秀的Windows系统镜像资源站,提供了丰富的Windows系统镜像资源,并且保证了资源的纯净和安全性,有需要的朋友可以去了解一下。这个非常实用的资源网站的创建者是国内的一个网友。_msdn我告诉你

vue2封装对话框el-dialog组件_<el-dialog 封装成组件 vue2-程序员宅基地

文章浏览阅读1.2k次。vue2封装对话框el-dialog组件_

MFC 文本框换行_c++ mfc同一框内输入二行怎么换行-程序员宅基地

文章浏览阅读4.7k次,点赞5次,收藏6次。MFC 文本框换行 标签: it mfc 文本框1.将Multiline属性设置为True2.换行是使用"\r\n" (宽字符串为L"\r\n")3.如果需要编辑并且按Enter键换行,还要将 Want Return 设置为 True4.如果需要垂直滚动条的话将Vertical Scroll属性设置为True,需要水平滚动条的话将Horizontal Scroll属性设_c++ mfc同一框内输入二行怎么换行

redis-desktop-manager无法连接redis-server的解决方法_redis-server doesn't support auth command or ismis-程序员宅基地

文章浏览阅读832次。检查Linux是否是否开启所需端口,默认为6379,若未打开,将其开启:以root用户执行iptables -I INPUT -p tcp --dport 6379 -j ACCEPT如果还是未能解决,修改redis.conf,修改主机地址:bind 192.168.85.**;然后使用该配置文件,重新启动Redis服务./redis-server redis.conf..._redis-server doesn't support auth command or ismisconfigured. try

实验四 数据选择器及其应用-程序员宅基地

文章浏览阅读4.9k次。济大数电实验报告_数据选择器及其应用

随便推点

灰色预测模型matlab_MATLAB实战|基于灰色预测河南省社会消费品零售总额预测-程序员宅基地

文章浏览阅读236次。1研究内容消费在生产中占据十分重要的地位,是生产的最终目的和动力,是保持省内经济稳定快速发展的核心要素。预测河南省社会消费品零售总额,是进行宏观经济调控和消费体制改变创新的基础,是河南省内人民对美好的全面和谐社会的追求的要求,保持河南省经济稳定和可持续发展具有重要意义。本文建立灰色预测模型,利用MATLAB软件,预测出2019年~2023年河南省社会消费品零售总额预测值分别为21881...._灰色预测模型用什么软件

log4qt-程序员宅基地

文章浏览阅读1.2k次。12.4-在Qt中使用Log4Qt输出Log文件,看这一篇就足够了一、为啥要使用第三方Log库,而不用平台自带的Log库二、Log4j系列库的功能介绍与基本概念三、Log4Qt库的基本介绍四、将Log4qt组装成为一个单独模块五、使用配置文件的方式配置Log4Qt六、使用代码的方式配置Log4Qt七、在Qt工程中引入Log4Qt库模块的方法八、获取示例中的源代码一、为啥要使用第三方Log库,而不用平台自带的Log库首先要说明的是,在平时开发和调试中开发平台自带的“打印输出”已经足够了。但_log4qt

100种思维模型之全局观思维模型-67_计算机中对于全局观的-程序员宅基地

文章浏览阅读786次。全局观思维模型,一个教我们由点到线,由线到面,再由面到体,不断的放大格局去思考问题的思维模型。_计算机中对于全局观的

线程间控制之CountDownLatch和CyclicBarrier使用介绍_countdownluach于cyclicbarrier的用法-程序员宅基地

文章浏览阅读330次。一、CountDownLatch介绍CountDownLatch采用减法计算;是一个同步辅助工具类和CyclicBarrier类功能类似,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。二、CountDownLatch俩种应用场景: 场景一:所有线程在等待开始信号(startSignal.await()),主流程发出开始信号通知,既执行startSignal.countDown()方法后;所有线程才开始执行;每个线程执行完发出做完信号,既执行do..._countdownluach于cyclicbarrier的用法

自动化监控系统Prometheus&Grafana_-自动化监控系统prometheus&grafana实战-程序员宅基地

文章浏览阅读508次。Prometheus 算是一个全能型选手,原生支持容器监控,当然监控传统应用也不是吃干饭的,所以就是容器和非容器他都支持,所有的监控系统都具备这个流程,_-自动化监控系统prometheus&grafana实战

React 组件封装之 Search 搜索_react search-程序员宅基地

文章浏览阅读4.7k次。输入关键字,可以通过键盘的搜索按钮完成搜索功能。_react search