通俗易懂注意力机制 注意力机制详解( 四 )


步骤5:计算softmax
from torch.nn.functional import softmax
attn_scores_softmax = softmax(attn_scores, dim=-1) # tensor([[6.3379e-02, 4.6831e-01, 4.6831e-01], # [6.0337e-06, 9.8201e-01, 1.7986e-02], # [2.9539e-04, 8.8054e-01, 1.1917e-01]])
# For readability, approximate the above as follows attn_scores_softmax = [ [0.0, 0.5, 0.5], [0.0, 1.0, 0.0], [0.0, 0.9, 0.1] ] attn_scores_softmax = torch.tensor(attn_scores_softmax
 
步骤6:将分数乘以值
 
weighted_values = values[:,None] * attn_scores_softmax.T[:,:,None]
# tensor([[[0.0000, 0.0000, 0.0000], # [0.0000, 0.0000, 0.0000], # [0.0000, 0.0000, 0.0000]], # # [[1.0000, 4.0000, 0.0000], # [2.0000, 8.0000, 0.0000], # [1.8000, 7.2000, 0.0000]], # # [[1.0000, 3.0000, 1.5000], # [0.0000, 0.0000, 0.0000], # [0.2000, 0.6000, 0.3000]]])
 
步骤7:求和加权值
 
outputs = weighted_values.sum(dim=0)
# tensor([[2.0000, 7.0000, 1.5000], # Output 1 # [2.0000, 8.0000, 0.0000], # Output 2 # [2.0000, 7.8000, 0.3000]]) # Output 3
 

注意:PyTorch 为此提供了一个 API nn.MultiheadAttention 。但是,此 API 要求你输入键、查询并估算 PyTorch 张量 。此外,该模块的输出经过线性变换 。
 
 
3.扩展到 Transfomers至此,我们接下来怎么做?Transfomers!确实,我们生活在深度学习研究和高计算资源令人兴奋的时代 。Transfomers 是论文《Attention Is All You Need》的成果,最初是为了进行神经机器翻译而生 。自此,研究人员开始进行组装、切割、添加和扩展,并将其用途扩展到更多的语言任务中 。
 
在这里,我将简单提一下如何将自注意力扩展到 Transformer 架构中 。
 
在自注意力模块中:
 
  • 尺寸
     
  • Bias
     
自注意力模块的输入:
 
  • 嵌入模块
     
  • 位置编码
     
  • 截断
     
  • 掩蔽
     
添加更多的自注意模块:
 
  • 多头
     
  • 层堆叠
     
自注意模块之间的模块:
 
  • 线性变换
     
  • 层范数
 


特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。