Attention的矩阵表示及理解

本文详细介绍了注意力机制在深度学习,特别是Seq2Seq模型中的应用。通过对比Luong和Vaswani的注意力机制,重点解释了Scaled Dot-Product Attention的工作原理,包括Attention Score的计算、Attention Distribution的softmax转换以及Attention Output的生成过程。文中还提供了矩阵运算的表示,帮助读者理解各个步骤,并给出了PyTorch实现的关键代码片段。

Attention两篇文章链接:其中一个是Luong,提的dot product attention, 另一个是Vaswali的scaled dot product attention , 也就是大名鼎鼎的attention is all you need。

说到attention不再过多赘述,论文中的公式推导感觉比较简单,结合自己的理解写一下矩阵层面的表示。数学好的可以跳过。

在attention is all you need这篇文章中,他是这么写的:
A t t e n t i o n ( Q , K , V ) = s o f t m a x ( Q K T d k ) V Attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d_k}})V Attention(Q,K,V)=softmax(dk QKT)V,而Luong那篇文章中,公式比较多且分散。
但无论如何,大致总结是(看下图),先算attention score(Q,K相乘),再用softmax算distribution,再把distribution和hidden state相乘获得attention output(最上面那个MatMul),再把output和另一个hidden相加(concat)。在这里插入图片描述

这里以seq2seq模型中的attention为例。

首先我们有encoder hidden state的一个序列: H = [ h 1 , h 2 , . . . h N ] H =[h_1, h_2, ...h_N] H=[h1,h2,...hN]
然后有 t t t 时刻的decoder state s t s^t st, 所有时刻的decoder state就是 S = [ s 1 , s 2 , . . . , s t ] S=[s^1, s^2, ..., s^t] S=[s1,s2,...,st]
每次用所有的encoder hidden state去和当前时刻的decoder state相乘(dot product)

对于 t t t时刻而言的attention score就是用 e t = [ h 1 T s t , h 2 T s t , . . . , h N T s t ] e^t = [h_1^Ts^t, h_2^Ts^t, ..., h_N^Ts^t] et=[h1Tst,h2Tst,...,hNTst]
但实际在计算中,我们是把整个decoder hidden state和encoder hidden state乘起来,而不是像循环一样对每个时刻都依次计算
E = [ h 1 T s 1 h 2 T s 1 , . . . , h N T s 1 ⋮ ⋮ ⋱ ⋮ h 1 T s t − 1 h 2 T s t − 1 , . . . , h N T s t − 1 h 1 T s t h 2 T s t , . . . , h N T s t ] = [ s 1 s 2 ⋮ s t ] ⋅ [ h 1 T h 2 T ⋯ h N T ]   ( 1 ) E = \left[ \begin{matrix} h_1^Ts^1 & h_2^Ts^1, &..., &h_N^Ts^1 \\ \vdots & \vdots &\ddots &\vdots\\ h_1^Ts^{t-1} & h_2^Ts^{t-1}, &..., &h_N^Ts^{t-1}\\ h_1^Ts^t & h_2^Ts^t, &..., &h_N^Ts^t \end{matrix} \right] = \left[ \begin{matrix}s^1\\ s^2\\ \vdots\\ s^t \end{matrix} \right] \cdot \left[ \begin{matrix} h_1^T & h_2^T & \cdots & & h_N^T \end{matrix} \right] \ (1) E=h1Ts1h1Tst1h1Tsth

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值