🚀 阶段三:GPT 架构 + 自回归训练 + 从零实现最小 GPT 模型

内容纲要

🌐 本阶段目录

  1. GPT 架构简介(vs BERT)
  2. 自回归语言建模原理(核心公式 + 图解)
  3. GPT-2 模型结构详解(Block-by-Block 拆解)
  4. 最小 GPT 模型实现(PyTorch)
  5. 训练一个玩具 GPT 模型(如:莎士比亚文本)
  6. 实时生成文本(逐词预测演示)

1️⃣ GPT 架构简介(vs BERT)

GPT:Generative Pretrained Transformer
本质:Decoder-only Transformer + 自回归训练

🧠 GPT 和 BERT 的结构对比

方面 BERT GPT
模型结构 Transformer Encoder Transformer Decoder
输入方式 双向(上下文都看) 单向(只能看前文)
训练目标 猜被 mask 的词(MLM) 猜下一个词(自回归)
应用领域 理解类任务 生成类任务(对话、写作)

2️⃣ 自回归语言模型原理

GPT 是一个典型的 自回归语言模型,也就是:

给定前 ( t ) 个词,预测第 ( t+1 ) 个词。

公式如下:

P(w_1, w_2, ..., w_n) = \prod_{t=1}^{n} P(w_t | w_1, ..., w_{t-1})

📊 示例:

输入句子片段:

The cat sat

模型预测下一个词概率分布:

on: 0.32
in: 0.12
with: 0.07
...

最终采样出概率最大的词:on


3️⃣ GPT-2 模型结构图解

GPT 的基础构件就是 Transformer Decoder Block:

[输入tokens]
    ↓
[词嵌入] + [位置编码]
    ↓
[多头 masked 自注意力]
    ↓
[前馈网络 FFN]
    ↓
[N 层堆叠]
    ↓
[输出 logits(词概率分布)]

🔒 Masked Self-Attention 关键:

  • 自注意力里不允许“看见未来”:
    [
    Attention(Q, K, V) \to 使用 mask 隐藏后续词
    ]

4️⃣ 最小 GPT 模型实现(纯 PyTorch,无依赖)

我们来实现一个超精简版 GPT:

✅ 结构参数

  • 词表大小:1000
  • 隐藏层维度:128
  • 层数:4
  • 注意力头数:4

📦 核心代码

import torch
import torch.nn as nn
import math

class GPTBlock(nn.Module):
    def __init__(self, dim, heads, ff_dim):
        super().__init__()
        self.attn = nn.MultiheadAttention(embed_dim=dim, num_heads=heads, batch_first=True)
        self.ff = nn.Sequential(
            nn.Linear(dim, ff_dim),
            nn.ReLU(),
            nn.Linear(ff_dim, dim)
        )
        self.norm1 = nn.LayerNorm(dim)
        self.norm2 = nn.LayerNorm(dim)

    def forward(self, x, attn_mask=None):
        x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x), attn_mask=attn_mask)[0]
        x = x + self.ff(self.norm2(x))
        return x

class MiniGPT(nn.Module):
    def __init__(self, vocab_size, dim=128, depth=4, heads=4, ff_dim=256, max_len=64):
        super().__init__()
        self.token_emb = nn.Embedding(vocab_size, dim)
        self.pos_emb = nn.Parameter(torch.randn(1, max_len, dim))
        self.blocks = nn.Sequential(*[GPTBlock(dim, heads, ff_dim) for _ in range(depth)])
        self.ln_f = nn.LayerNorm(dim)
        self.head = nn.Linear(dim, vocab_size)

    def forward(self, idx):
        B, T = idx.shape
        x = self.token_emb(idx) + self.pos_emb[:, :T]
        attn_mask = torch.tril(torch.ones(T, T)).to(idx.device)
        attn_mask = attn_mask == 0  # 为 MultiheadAttention 生成 bool mask
        x = self.blocks(x, attn_mask=attn_mask)
        x = self.ln_f(x)
        return self.head(x)  # (B, T, vocab_size)

5️⃣ 训练玩具模型(例如:莎士比亚文本)

你可以直接喂入几十KB的小语料:

# 用字符串构建 vocab 和 dataset
text = "to be or not to be that is the question ..."
chars = sorted(list(set(text)))
stoi = {ch:i for i,ch in enumerate(chars)}
itos = {i:ch for ch,i in stoi.items()}
vocab_size = len(chars)

def encode(s): return [stoi[c] for c in s]
def decode(l): return ''.join([itos[i] for i in l])

data = torch.tensor(encode(text), dtype=torch.long)

用前 64 个字符预测下一个字符,训练方式和语言建模一致。


6️⃣ 实时生成演示(逐词生成)

def generate(model, idx, max_new_tokens):
    model.eval()
    for _ in range(max_new_tokens):
        logits = model(idx)[:, -1, :]  # 最后一个位置
        probs = torch.softmax(logits, dim=-1)
        next_token = torch.multinomial(probs, num_samples=1)
        idx = torch.cat([idx, next_token], dim=1)
    return idx

# 示例:输入 "to be", 生成 20 个字符
start = torch.tensor([[stoi[c] for c in "to be"]])
output = generate(model, start, max_new_tokens=20)
print(decode(output[0].tolist()))

✅ 总结一波

你掌握了
GPT 架构和 BERT 区别
自回归语言建模原理
GPT-2 Block-by-Block 结构
从零搭建最小 GPT 模型
文本生成与采样

🔜 接下来干嘛?

进入最终 Boss 战——ChatGPT 背后的全流程机制拆解!

✅ 阶段四:ChatGPT = GPT + 微调 + RLHF + 多模态 + Agent + RAG
✅ 结构图 + 模块关系图
✅ PPO 训练代码讲解
✅ 如何接入 RAG 构建你自己的 ChatGPT
✅ Agent 多轮规划任务示例

后续路线:

  1. Transformer 结构和实现(已完成✅)
  2. BERT 的结构 + 预训练任务 + 实现(含微调任务)(已完成✅)
  3. GPT 架构 + 自回归训练 + 从头训练一个玩具 GPT(已完成✅)
  4. 🔜 ChatGPT 的训练流程拆解(含 RLHF、RAG、Agent)
  5. 🔜 实战项目:从 Prompt 到 Fine-tune 的完整链路演练

3 Comments

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward