Encoder-Decoder Attention(Cross-Attention)详解

Mussy Hu

Cross-Attention 是什么?

Cross-Attention(交叉注意力)允许 Decoder 的每个词,去关注 Encoder 输出的任意位置,提取源句子上下文信息,辅助生成目标句子。

比如:
源句子(英文):The cat sat on the mat
目标句子(法语):Le chat s’est assis…
→ 当 Decoder 生成 assis,它可以 attend 到 Encoder 中的 sat


Cross-Attention 的结构和计算

它跟普通 Self-Attention 长得很像,但不同之处在于:

  • Query (Q):来自 Decoder 的前一层输出

  • Key / Value (K/V):来自 Encoder 的输出(编码后的源句信息)

模块公式:

1
2
3
Q = Linear(decoder_output)
K = Linear(encoder_output)
V = Linear(encoder_output)

然后计算 Attention:

1
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) @ V

总体流程图如下:

1
2
3
4
5
6
7
8
9
  Decoder 中前一层输出(已编码目标前文)

Q(查询)

Encoder 输出(整句源语言表示) → K / V

Attention(Q, K, V)

加权聚合的源句信息(每个目标词都不一样)

为什么这很关键

这个 Attention 让模型在生成每一个目标词时,选择性关注源句的不同部分,相当于翻译时的“对齐机制”。

比如:

目标词 注意力关注的源词
Le The
chat cat
assis sat

注意:Cross-Attention 不需要遮挡 Mask,因为可以看完整个源句子。


Cross-Attention 输出了什么?

它输出的是一个与目标序列长度相同的向量序列,其中每个向量:

表示目标当前词,在 Encoder 输出的所有位置中,注意力加权之后的聚合表示。

也就是说:“我要生成这个词时,我从源句那边‘挑’了一些信息过来”。


后续处理(残差连接 + LayerNorm)

和之前模块一样,Cross-Attention 的输出也会走这条路:

1
2
x = x + cross_attn_output
x = layernorm(x)

这样保持稳定性、训练效果好。


小结一下 Cross-Attention 的意义

特点 说明
输入 Query 来自 Decoder,K/V 来自 Encoder
作用 让目标序列在生成时“借助”源语言信息
应用场景 机器翻译、摘要、对话生成等所有 Encoder-Decoder 架构中
输出 每个目标词所提取的“源句上下文特征”

  • 标题: Encoder-Decoder Attention(Cross-Attention)详解
  • 作者: Mussy Hu
  • 创建于 : 2025-03-13 00:00:00
  • 更新于 : 2025-05-20 15:05:42
  • 链接: https://blog.musdrop.com/2025/03/13/Encoder-Decoder Attention(Cross-Attention)详解/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。