1
2
3
import torch.nn as nn
import torch
import torch.nn.functional as F

1. 词嵌入 (Word Embedding)

令源语言词表大小为 $|\mathcal{V}_s|$,目标语言词表大小为 $|\mathcal{V}_t|$,嵌入维度为 $d_{\text{model}}$。
对输入序列中的每个 token $x_i$(整数索引),其嵌入向量为:

$$ \mathbf{e}_i = \text{Embedding}(x_i) \in \mathbb{R}^{d_{\text{model}}} $$

嵌入矩阵 $ \mathbf{E}_s \in \mathbb{R}^{|\mathcal{V}_s| \times d_{\text{model}}} $,目标嵌入同理 $ \mathbf{E}_t $。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Embedding(nn.Module):
    "词嵌入"
    def __init__(self, num_embeddings: int,
                 embedding_dim: int,
                 padding_index: int):
        super().__init__()
        self.padding_index = padding_index
        self.weight = nn.Parameter(torch.randn(num_embeddings, embedding_dim))
        self.weight[padding_index] = 0.0
        self.weight.register_hook(self._zero_out_gradients)

    def _zero_out_gradients(self, grad):
        # 每次反向传播后,自动把 freeze_ids 位置的梯度设为 0
        grad[self.padding_index] = 0.0
        return grad

    def forward(self, x: torch.Tensor):
        """
        batch_size:批次大小(一次处理的句子数量)。
        seq_len:序列长度(句子中的单词或标记数量)。
        embedding_dim:嵌入维度(每个单词映射到的向量维度,如 512 或 768)
        输入x形状:[batch_size, seq_len]
        返回x形状:[batch_size, seq_len, embedding_dim]
        """
        return self.weight[x]

2. 位置编码 (Positional Encoding)

对位置 $ pos $ 和维度 $ i $($0 \le i \lt d_{\text{model}}$):

$$ \begin{aligned} PE(pos, 2i) &= \sin\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right) \\ PE(pos, 2i+1) &= \cos\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right) \end{aligned} $$

位置编码矩阵 $ \mathbf{P} \in \mathbb{R}^{L_{\text{max}} \times d_{\text{model}}} $ 与序列长度无关,训练后固定。


3. 输入表示 (Input Representation)

对于长度为 $L$ 的序列,嵌入与位置编码相加:

$$ \mathbf{h}_i^{(0)} = \mathbf{e}_i + \mathbf{P}_i, \quad i = 1,\dots,L $$

得到第一层的输入矩阵 $ \mathbf{H}^{(0)} \in \mathbb{R}^{L \times d_{\text{model}}} $。


4. Dropout

Dropout 在训练时以概率 $p$ 随机将输入张量的某些元素置零,并缩放 $1/(1-p)$ 以保持期望不变。记 $\text{Dropout}(\cdot)$ 为训练时的随机算子,在推理时变为恒等映射。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class PositionalEncoding(nn.Module):
    "位置编码"

    def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
        super().__init__()
        self.dropout = nn.Dropout(p=dropout)
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(0, max_len).unsqueeze(1)
        div_term = torch.exp(torch.arange(0, d_model, 2)
                             * -(F.math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)
        pe = pe.unsqueeze(0)
        self.register_buffer("pe", pe)

    def forward(self, x):
        return self.dropout(x
            + self.pe[:, :x.size(1)].requires_grad_(False))

5. 缩放点积注意力 (Scaled Dot-Product Attention)

给定查询 $ \mathbf{Q} \in \mathbb{R}^{L_q \times d_k} $,键 $ \mathbf{K} \in \mathbb{R}^{L_k \times d_k} $,值 $ \mathbf{V} \in \mathbb{R}^{L_k \times d_v} $:

$$ \text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\left( \frac{\mathbf{Q} \mathbf{K}^\top}{\sqrt{d_k}} \right) \mathbf{V} $$

其中 softmax 按行作用于矩阵。


6. 多头注意力 (Multi-Head Attention)

设头数 $h$,每个头的维度 $d_k = d_v = d_{\text{model}} / h$。对每个头 $i$:

$$ \begin{aligned} \mathbf{Q}_i &= \mathbf{Q} \mathbf{W}_i^Q, \quad \mathbf{K}_i = \mathbf{K} \mathbf{W}_i^K, \quad \mathbf{V}_i = \mathbf{V} \mathbf{W}_i^V \\ \mathbf{head}_i &= \text{Attention}(\mathbf{Q}_i, \mathbf{K}_i, \mathbf{V}_i) \end{aligned} $$

其中 $\mathbf{W}_i^Q, \mathbf{W}_i^K \in \mathbb{R}^{d_{\text{model}} \times d_k}, \mathbf{W}_i^V \in \mathbb{R}^{d_{\text{model}} \times d_v}$。然后拼接所有头并投影:

$$ \text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{Dropout}\left( \text{Concat}(\mathbf{head}_1, \dots, \mathbf{head}_h) \mathbf{W}^O \right) $$

其中 $\mathbf{W}^O \in \mathbb{R}^{h d_v \times d_{\text{model}}}$,Dropout 应用于输出。


多头注意力输入的形状

注意力类型Query 形状Key 形状Value 形状
编码器自注意力(batch, src_len, d_model)(batch, src_len, d_model)(batch, src_len, d_model)
解码器掩码自注意力(batch, tgt_len, d_model)(batch, tgt_len, d_model)(batch, tgt_len, d_model)
解码器交叉注意力(batch, tgt_len, d_model)(batch, src_len, d_model)(batch, src_len, d_model)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model: int, nhead: int = 8, 
                 dropout: float = 0.1):
        super().__init__()
        self.d_model = d_model
        self.nhead = nhead
        self.d_k = d_model // nhead
        self.W_q = nn.Linear(d_model, d_model)
        self.in_proj_kv = nn.Linear(d_model, 2 * d_model)
        self.out_proj = nn.Linear(d_model, d_model)
        self.dropout = nn.Dropout(p=dropout)

    def forward(self, query: torch.Tensor,
                key: torch.Tensor = None,
                value: torch.Tensor = None,
                attn_mask=None, key_padding_mask=None):
        batch_size = query.size(0)

        if key is None:
            key = query
        if value is None:
            value = query

        q_len = query.size(1)
        k_len = key.size(1)
        v_len = value.size(1)

        Q = self.W_q(query)
        K, V = self.in_proj_kv(key).chunk(2, dim=-1)

        Q = Q.view(batch_size, q_len, self.nhead, -1).transpose(1, 2)  # (batch_size, num_heads, q_len, d_model // nhead)
        K = K.view(batch_size, k_len, self.nhead, -1).transpose(1, 2)  # (batch_size, num_heads, k_len, d_model // nhead)
        V = V.view(batch_size, v_len, self.nhead, -1).transpose(1, 2)  # (batch_size, num_heads, v_len, d_model // nhead)

        scores = Q @ K.transpose(-2, -1) / (self.d_k ** 0.5)  # [batch_size, num_heads, seq_q, seq_k]
        if attn_mask is not None:
            scores = scores + attn_mask  # 因果掩码,通常里面是 -inf
        if key_padding_mask is not None:
            # padding 掩码,把 True 的位置变成 -inf
            scores = scores \
                .masked_fill(
                    key_padding_mask.unsqueeze(1).unsqueeze(2),
                    float('-inf')
                )

        context = self.dropout(F.softmax(scores, dim=-1)) @ V

        context = context.transpose(1, 2)
        output = context.contiguous().view(batch_size, q_len, self.d_model)
        return self.out_proj(output)

7. 前馈网络 (Position-wise Feed-Forward Network)

对每个位置独立进行相同的两层线性变换,中间有激活函数(通常 ReLU):

$$ \text{FFN}(\mathbf{x}) = \text{ReLU}(\mathbf{x} \mathbf{W}_1 + \mathbf{b}_1) \mathbf{W}_2 + \mathbf{b}_2 $$

其中 $\mathbf{W}_1 \in \mathbb{R}^{d_{\text{model}} \times d_{ff}}$,$\mathbf{W}_2 \in \mathbb{R}^{d_{ff} \times d_{\text{model}}}$,通常 $d_{ff} = 4 d_{\text{model}}$。训练时可在第一个线性层后应用 Dropout(有时也在激活后)。


8. 层归一化 (Layer Normalization)

对每个样本的每个特征维度独立进行归一化(不同于 BatchNorm)。设输入 $\mathbf{x} \in \mathbb{R}^{d_{\text{model}}}$:

$$ \text{LayerNorm}(\mathbf{x}) = \gamma \odot \frac{\mathbf{x} - \mu}{\sigma} + \beta $$

其中 $\mu = \frac{1}{d_{\text{model}}} \sum_{i=1}^{d_{\text{model}}} x_i$,$\sigma^2 = \frac{1}{d_{\text{model}}} \sum_{i=1}^{d_{\text{model}}} (x_i - \mu)^2$,$\gamma, \beta$ 为可学习参数。


9. 编码器层 (Encoder Layer)

每个编码器层包含两个子层,每个子层采用残差连接 + 层归一化(Post-LN 原版,或 Pre-LN 变体,此处以 Post-LN 为例):

$$ \begin{aligned} \mathbf{X}' &= \mathbf{X} + \text{Dropout}\big( \text{MultiHead}(\mathbf{X}, \mathbf{X}, \mathbf{X}) \big) \\ \mathbf{X}'' &= \text{LayerNorm}(\mathbf{X}') \\ \mathbf{X}''' &= \mathbf{X}'' + \text{Dropout}\big( \text{FFN}(\mathbf{X}'') \big) \\ \mathbf{X}_{\text{out}} &= \text{LayerNorm}(\mathbf{X}''') \end{aligned} $$

其中 $\mathbf{X}$ 为该层的输入,$\mathbf{X}_{\text{out}}$ 为输出。在 PyTorch 的 nn.TransformerEncoderLayer 中,顺序是:自注意力 → dropout → 残差 → 层归一化 → FFN → dropout → 残差 → 层归一化。常见实现为 Pre-LN(更稳定):

$$ \begin{aligned} \mathbf{X}' &= \mathbf{X} + \text{Dropout}\big( \text{MultiHead}(\text{LayerNorm}(\mathbf{X}), \text{LayerNorm}(\mathbf{X}), \text{LayerNorm}(\mathbf{X})) \big) \\ \mathbf{X}_{\text{out}} &= \mathbf{X}' + \text{Dropout}\big( \text{FFN}(\text{LayerNorm}(\mathbf{X}')) \big) \end{aligned} $$

(以下公式以 Pre-LN 为准,因为现代训练更常用。)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class EncoderLayer(nn.Module):
    def __init__(self, d_model: int, nhead: int = 8, dropout: float = 0.1):
        super().__init__()
        self.mha = MultiHeadAttention(d_model, nhead, dropout)
        self.norm1 = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_model * 4),
            nn.ReLU(),
            nn.Dropout(p=dropout),
            nn.Linear(d_model * 4, d_model)
        )
        self.norm2 = nn.LayerNorm(d_model)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)

    # 1. Post-LN(原始 Transformer 论文中的顺序) 先做残差连接、后做归一化
    # x = LayerNorm(x + Dropout(SubLayer(x)))
    # 2. Pre-LN(更现代的变体)先层归一化,再进入子层,然后残差连接。
    # x = x + Dropout(SubLayer(LayerNorm(x)))
    def forward(self, x, key_padding_mask=None):
        x = x + self.dropout1(self.mha(self.norm1(x), key_padding_mask=key_padding_mask))
        x = x + self.dropout2(self.ffn(self.norm2(x)))
        return x

 
class Encoder(nn.Module):
    def __init__(self, d_model: int, nhead: int = 8,
                 dropout: float = 0.1,
                 num_encoder_layers: int = 6):
        super().__init__()
        self.layers = nn.ModuleList(
            [EncoderLayer(d_model, nhead, dropout)
             for _ in range(num_encoder_layers)]
        )

    def forward(self, x: torch.Tensor, key_padding_mask=None):
        for layer in self.layers:
            x = layer(x, key_padding_mask=key_padding_mask)
        return x

10. 解码器层 (Decoder Layer)

解码器层有三个子层:带掩码的自注意力、交叉注意力、前馈网络。同样使用 Pre-LN:

$$ \begin{aligned} \mathbf{X}_1 &= \mathbf{X} + \text{Dropout}\big( \text{MaskedMultiHead}(\text{LayerNorm}(\mathbf{X}), \text{LayerNorm}(\mathbf{X}), \text{LayerNorm}(\mathbf{X})) \big) \\ \mathbf{X}_2 &= \mathbf{X}_1 + \text{Dropout}\big( \text{MultiHead}(\text{LayerNorm}(\mathbf{X}_1), \text{LayerNorm}(\mathbf{Y}), \text{LayerNorm}(\mathbf{Y})) \big) \\ \mathbf{X}_{\text{out}} &= \mathbf{X}_2 + \text{Dropout}\big( \text{FFN}(\text{LayerNorm}(\mathbf{X}_2)) \big) \end{aligned} $$

其中 $\mathbf{Y}$ 是编码器最后一层的输出。MaskedMultiHead 在自注意力中对未来位置应用掩码(上三角矩阵 $-\infty$)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class DecoderLayer(nn.Module):
    def __init__(self, d_model: int, nhead: int = 8, dropout: float = 0.1):
        super().__init__()
        self.masked_mha = MultiHeadAttention(d_model, nhead, dropout)
        self.norm1 = nn.LayerNorm(d_model)

        self.cross_mha = MultiHeadAttention(d_model, nhead, dropout)
        self.norm2 = nn.LayerNorm(d_model)

        # 3. 前馈网络
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_model * 4),
            nn.ReLU(),
            nn.Dropout(p=dropout),
            nn.Linear(d_model * 4, d_model)
        )
        self.norm3 = nn.LayerNorm(d_model)

        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)
        self.dropout3 = nn.Dropout(dropout)

    def forward(self, tgt, memory, tgt_mask=None,
                tgt_key_padding_mask=None,
                memory_key_padding_mask=None):
        x = tgt + self.dropout1(
            self.masked_mha(self.norm1(tgt),
                            attn_mask=tgt_mask,
                            key_padding_mask=tgt_key_padding_mask)
        )

        x = x + self.dropout2(
            self.cross_mha(query=self.norm2(x), key=memory,
                           value=memory,
                           key_padding_mask=memory_key_padding_mask)
        )

        x = x + self.dropout3(self.ffn(self.norm3(x)))
        return x


class Decoder(nn.Module):
    def __init__(self, d_model: int, nhead: int = 8,
                 dropout: float = 0.1,
                 num_decoder_layers: int = 6):
        super().__init__()
        self.layers = nn.ModuleList(
            [DecoderLayer(d_model, nhead, dropout)
             for i in range(num_decoder_layers)]
        )

    def forward(self, tgt: torch.Tensor,
                memory: torch.Tensor,
                tgt_mask=None,
                tgt_key_padding_mask=None,
                memory_key_padding_mask=None):
        for layer in self.layers:
            tgt = layer(tgt, memory, tgt_mask,
                        tgt_key_padding_mask,
                        memory_key_padding_mask)
        return tgt

11. 输出层与损失函数

解码器最后输出 $\mathbf{H}_{\text{dec}} \in \mathbb{R}^{L_t \times d_{\text{model}}}$,通过线性层和 softmax 得到每个位置的概率分布:

$$ \mathbf{P} = \text{softmax}\big( \mathbf{H}_{\text{dec}} \mathbf{W}_{\text{out}} + \mathbf{b}_{\text{out}} \big) \in \mathbb{R}^{L_t \times |\mathcal{V}_t|} $$

其中 $\mathbf{W}_{\text{out}} \in \mathbb{R}^{d_{\text{model}} \times |\mathcal{V}_t|}$。训练时使用交叉熵损失,对非 padding 位置求平均:

$$ \mathcal{L} = -\frac{1}{\sum_{t} \mathbf{1}_{\{y_t \neq \text{pad}\}}} \sum_{t=1}^{L_t} \mathbf{1}_{\{y_t \neq \text{pad}\}} \log P(y_t | y_{\lt t}, X) $$

12. 整体前向传播流程(数学形式)

给定源序列 $X = (x_1, \dots, x_{L_s})$ 和目标序列 $Y = (y_1, \dots, y_{L_t})$(训练时已知):

  1. 源嵌入:$\mathbf{E}_s = \text{Embedding}(X) + \mathbf{P}_{1:L_s}$,形状 $(L_s, d_{\text{model}})$。
  2. 编码器:通过 $N$ 个编码器层,输出 $\mathbf{C} = \text{Encoder}(\mathbf{E}_s)$。
  3. 目标嵌入:$\mathbf{E}_t = \text{Embedding}(Y) + \mathbf{P}_{1:L_t}$。
  4. 解码器:通过 $N$ 个解码器层(使用掩码自注意力和交叉注意力),输出 $\mathbf{H}_{\text{dec}} = \text{Decoder}(\mathbf{E}_t, \mathbf{C})$。
  5. 输出层:$\mathbf{P} = \text{softmax}(\mathbf{H}_{\text{dec}} \mathbf{W}_{\text{out}} + \mathbf{b}_{\text{out}})$。
  6. 损失:计算交叉熵(忽略 pad)。

以上表达式完整覆盖了 Transformer 的所有组件,包括嵌入、位置编码、Dropout、注意力、残差、层归一化、前馈网络以及输出层。训练时 Dropout 生效,推理时关闭。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Transformer(nn.Module):
    def __init__(self, d_model: int,
                 nhead: int = 8,
                 dropout: float = 0.1,
                 num_encoder_layers: int = 6,
                 num_decoder_layers: int = 6):
        super().__init__()
        self.encoder = Encoder(d_model, nhead,
                               dropout, num_encoder_layers)
        self.decoder = Decoder(d_model, nhead,
                               dropout, num_decoder_layers)

    def forward(self, src, tgt, tgt_mask,
                src_key_padding_mask,
                tgt_key_padding_mask):

        # 1. 编码器跑完,得到 memory
        memory = self.encoder(src, key_padding_mask=src_key_padding_mask)

        # 2. 解码器拿着 tgt 和 memory 跑完
        # 注意:src 的 padding 掩码,在解码器里变成了 memory_key_padding_mask!
        out = self.decoder(tgt, memory,
                           tgt_mask=tgt_mask,
                           tgt_key_padding_mask=tgt_key_padding_mask,
                           memory_key_padding_mask=src_key_padding_mask)
        return out