🌟 Grouped Query Attention (GQA) 核心公式

GQA 的目标是减少 Key/Value 的数量,通过引入共享的 Key/Value 组,实现更高效的计算。

设:

  • x∈RT×dx \in \mathbb{R}^{T \times d}x∈RT×d 是输入序列;
  • hhh 为总头数,ggg 为 K/V 分组数(通常 g<hg < hg<h);
  • 每组包含 hg=hgh_g = \frac{h}{g}hg​=gh​ 个 Query;
  • 每个头的维度为 dh=dhd_h = \frac{d}{h}dh​=hd​。

✅ Query/Key/Value 计算

Q=xWQ,K=xWK,V=xWV Q = xW^Q,\quad K = xW^K,\quad V = xW^V Q=xWQ,K=xWK,V=xWV

其中:

  • Q∈RT×h×dhQ \in \mathbb{R}^{T \times h \times d_h}Q∈RT×h×dh​
  • K,V∈RT×g×dhK, V \in \mathbb{R}^{T \times g \times d_h}K,V∈RT×g×dh​

说明:Q 拆分成 hhh 个头,K 和 V 只拆分成 ggg 个组,每 hgh_ghg​ 个 Q 共享一组 K/V。


✅ 注意力权重计算(每个头 iii)

令 j=⌊ihg⌋j = \left\lfloor \frac{i}{h_g} \right\rfloorj=⌊hg​i​⌋,表示第 iii 个头对应第 jjj 个 K/V 组:

Attentioni=softmax(QiKj⊤dh)Vj \text{Attention}_i = \text{softmax}\left( \frac{Q_i K_j^\top}{\sqrt{d_h}} \right)V_j Attentioni​=softmax(dh​​Qi​Kj⊤​​)Vj​


✅ 最终输出拼接

Output=Concat(Attention1,…,Attentionh)WO \text{Output} = \text{Concat}(\text{Attention}_1, \ldots, \text{Attention}_h)W^O Output=Concat(Attention1​,…,Attentionh​)WO

其中 WOW^OWO 为输出变换矩阵。


📌 总结

GQA 在保持多头 Query 精度的同时,大幅减少了 Key/Value 的计算和存储开销,适用于大规模模型(如 LLaMA 2/3、Qwen2 等)。

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐