Transformer 架构解析

深入理解 Self-Attention、Multi-Head Attention 与位置编码。

zyssnh 2026/05/20

Self-Attention 机制

Transformer 的核心是缩放点积注意力

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left( \frac{QK^T}{\sqrt{d_k}} \right) V

Multi-Head Attention

多头注意力将查询、键、值投影到 hh 个子空间:

MultiHead(Q,K,V)=Concat(head1,,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) W^O

其中 headi=Attention(QWiQ,KWiK,VWiV)\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)

import torch.nn as nn

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, n_heads):
        super().__init__()
        self.d_k = d_model // n_heads
        self.n_heads = n_heads
        self.q_linear = nn.Linear(d_model, d_model)
        self.k_linear = nn.Linear(d_model, d_model)
        self.v_linear = nn.Linear(d_model, d_model)
        self.out = nn.Linear(d_model, d_model)

位置编码

Transformer 使用正弦位置编码注入序列信息:

PE(pos,2i)=sin(pos100002i/dmodel)PE_{(pos, 2i)} = \sin\left( \frac{pos}{10000^{2i/d_{model}}} \right) PE(pos,2i+1)=cos(pos100002i/dmodel)PE_{(pos, 2i+1)} = \cos\left( \frac{pos}{10000^{2i/d_{model}}} \right)

理解 Self-Attention 需要线性代数基础中的矩阵乘法知识。概率论基础支撑了 softmax 归一化的理论基础。

Transformer 是机器学习概述中深度学习范式的里程碑式架构。

反向链接 ←

0

暂无节点链接到此处

出链 0 入链 0