Transformer 从零手写:PyTorch 实现详解(上)

2026-09-25 · 学习教程 · 阅读 20 分钟 · 作者:老K

“Attention is all you need” 发表快十年了,但真正手写过一遍 Transformer 的人并不多。这篇教程带你用 300 行 PyTorch 代码,从零实现一个能跑的 GPT 风格模型。不调 nn.Transformer,全部手写。

前置要求:Python 基础、PyTorch 张量操作、知道什么是 softmax。一块能跑 CUDA 的显卡会更快,但 CPU 也能跑通(慢点)。

一、Scaled Dot-Product Attention

Transformer 的核心就一行公式:

Attention(Q, K, V) = softmax(QKT / √dk) V

翻译成人话:Query 和每个 Key 算相似度,softmax 归一化后作为权重,对 Value 加权求和。除以 √dk 是为了防止点积过大导致 softmax 梯度消失。

import torch
import torch.nn as nn
import math

class ScaledDotProductAttention(nn.Module):
    def __init__(self, dropout=0.1):
        super().__init__()
        self.dropout = nn.Dropout(dropout)

    def forward(self, Q, K, V, mask=None):
        # Q, K, V: (batch, heads, seq_len, d_k)
        d_k = Q.size(-1)
        scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(d_k)

        if mask is not None:
            scores = scores.masked_fill(mask == 0, -1e9)

        attn = torch.softmax(scores, dim=-1)
        attn = self.dropout(attn)
        return torch.matmul(attn, V), attn

二、Multi-Head Attention

单头 Attention 只能关注一种模式,多头就是并行跑 h 个 Attention,然后拼起来:

  1. 输入 X 分别乘以 WQ、WK、WV 得到 Q、K、V
  2. 切分成 h 个头,每个头独立做 Attention
  3. 拼回 + 线性投影 WO
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model=512, num_heads=8, dropout=0.1):
        super().__init__()
        assert d_model % num_heads == 0
        self.d_k = d_model // num_heads
        self.num_heads = num_heads

        self.W_q = nn.Linear(d_model, d_model)
        self.W_k = nn.Linear(d_model, d_model)
        self.W_v = nn.Linear(d_model, d_model)
        self.W_o = nn.Linear(d_model, d_model)
        self.attn = ScaledDotProductAttention(dropout)

    def split_heads(self, x):
        # (batch, seq, d_model) -> (batch, heads, seq, d_k)
        b, s, _ = x.size()
        return x.view(b, s, self.num_heads, self.d_k).transpose(1, 2)

    def forward(self, q, k, v, mask=None):
        Q = self.split_heads(self.W_q(q))
        K = self.split_heads(self.W_k(k))
        V = self.split_heads(self.W_v(v))
        out, attn = self.attn(Q, K, V, mask)
        # 拼回: (batch, heads, seq, d_k) -> (batch, seq, d_model)
        out = out.transpose(1, 2).contiguous().view(
            q.size(0), q.size(1), -1)
        return self.W_o(out)

三、位置编码:给模型“方向感”

Attention 本身是 permutation-invariant 的(打乱顺序结果不变),所以必须注入位置信息。原论文用正弦编码:

class PositionalEncoding(nn.Module):
    def __init__(self, d_model=512, max_len=5000):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        pos = torch.arange(0, max_len).unsqueeze(1).float()
        div = torch.exp(torch.arange(0, d_model, 2).float()
                        * -(math.log(10000.0) / d_model))
        pe[:, 0::2] = torch.sin(pos * div)
        pe[:, 1::2] = torch.cos(pos * div)
        self.register_buffer('pe', pe.unsqueeze(0))

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

为什么用 sin/cos 而不是直接学一个 embedding?因为三角函数有相对位置的线性性质:PE(pos+k) 可以表示为 PE(pos) 的线性变换,模型更容易泛化到没见过的长度。

下篇预告

下篇我们将实现 Encoder/Decoder 层、完整的 Transformer 模型,并在 tiny-shakespeare 数据集上训练一个能生成文本的 mini-GPT。还会讲讲现代 LLM 的改进:RoPE、GQA、SwiGLU 这些都是怎么来的。

完整代码已上传 GitHub,Colab 一键运行版本在评论区置顶。下一篇见!