广告位 728x90 顶部通栏广告 ¥2000/月

Transformer模型源码解析:以BERT为例

深入BERT源码,理解Transformer实现细节

高级 40 学时 42 浏览 2026-07-06
广告位 468x60 正文内嵌广告1 ¥500/月

课程简介

课程简介

本课程通过解析BERT模型源码,深入讲解Transformer的实现细节,包括自注意力计算、层归一化、残差连接等核心组件的代码实现。课程结合理论分析与实战代码,帮助学员从底层理解Transformer的工作原理,提升代码实现能力。适合有一定Transformer基础且希望深入源码的学员。

课程大纲

第1章第一章 BERT模型概述
  • 1.1 BERT背景与意义30min
  • 1.2 BERT整体架构45min
第2章第二章 核心组件源码解析
  • 2.1 自注意力计算90min
  • 2.2 层归一化与残差连接60min
  • 2.3 位置编码实现60min
第3章第三章 训练与微调代码分析
  • 3.1 预训练代码60min
  • 3.2 微调代码60min
广告位 336x280 正文内嵌广告2 ¥700/月

课程资料

Transformer模型源码解析:以BERT为例

第一章 BERT模型概述

1.1 BERT背景与意义

BERT(Bidirectional Encoder Representations from Transformers)是Google于2018年提出的预训练语言模型,其核心思想是通过双向Transformer编码器学习文本的深层语义表示。BERT的出现推动了NLP领域从"任务特定模型"向"预训练+微调"范式的转变,在GLUE、SQuAD等基准测试中取得了显著突破。

BERT的关键创新包括:

  1. 双向上下文建模:通过Masked Language Model(MLM)任务同时利用左右上下文
  2. 大规模无监督预训练:在Wikipedia+BookCorpus(33亿词)上训练
  3. 统一的架构:同一模型适用于多种下游任务

1.2 BERT整体架构

BERT的架构基于标准Transformer编码器,主要组件包括:

  • 输入嵌入层:词嵌入+位置嵌入+分段嵌入
  • 多层Transformer编码器:12层(Base版)或24层(Large版)
  • 任务特定输出层:针对不同任务的简单分类器
graph TD A[输入文本] --> B[Token Embedding] A --> C[Position Embedding] A --> D[Segment Embedding] B --> E[Embedding Sum] C --> E D --> E E --> F[Transformer Encoder x12] F --> G[Pooler/Classifier]

BERT的输入表示是三种嵌入的求和:

# 简化版输入嵌入实现
import torch
import torch.nn as nn

class BertEmbeddings(nn.Module):
    def __init__(self, vocab_size, hidden_size, max_position_embeddings, type_vocab_size):
        super().__init__()
        self.word_embeddings = nn.Embedding(vocab_size, hidden_size)
        self.position_embeddings = nn.Embedding(max_position_embeddings, hidden_size)
        self.token_type_embeddings = nn.Embedding(type_vocab_size, hidden_size)
        self.LayerNorm = nn.LayerNorm(hidden_size)
        self.dropout = nn.Dropout(0.1)

    def forward(self, input_ids, token_type_ids=None, position_ids=None):
        seq_length = input_ids.size(1)
        if position_ids is None:
            position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
            position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
        if token_type_ids is None:
            token_type_ids = torch.zeros_like(input_ids)
            
        words_embeddings = self.word_embeddings(input_ids)
        position_embeddings = self.position_embeddings(position_ids)
        token_type_embeddings = self.token_type_embeddings(token_type_ids)
        
        embeddings = words_embeddings + position_embeddings + token_type_embeddings
        embeddings = self.LayerNorm(embeddings)
        embeddings = self.dropout(embeddings)
        return embeddings

本节小结

  • BERT通过MLM和NSP任务实现双向上下文建模
  • 输入表示是词、位置、分段三种嵌入的求和
  • 核心架构由多层Transformer编码器堆叠而成

第二章 核心组件源码解析

2.1 自注意力计算

自注意力(Self-Attention)是Transformer的核心机制,BERT采用多头注意力(Multi-Head Attention)实现并行计算。以下是HuggingFace实现中的关键代码:

# 简化版多头注意力实现
class BertSelfAttention(nn.Module):
    def __init__(self, hidden_size, num_attention_heads, attention_probs_dropout_prob):
        super().__init__()
        if hidden_size % num_attention_heads != 0:
            raise ValueError(f"hidden_size {hidden_size} must be divisible by num_attention_heads {num_attention_heads}")
            
        self.num_attention_heads = num_attention_heads
        self.attention_head_size = int(hidden_size / num_attention_heads)
        self.all_head_size = self.num_attention_heads * self.attention_head_size

        self.query = nn.Linear(hidden_size, self.all_head_size)
        self.key = nn.Linear(hidden_size, self.all_head_size)
        self.value = nn.Linear(hidden_size, self.all_head_size)

        self.dropout = nn.Dropout(attention_probs_dropout_prob)

    def transpose_for_scores(self, x):
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = x.view(*new_x_shape)
        return x.permute(0, 2, 1, 3)  # [batch, head, seq_len, head_dim]

    def forward(self, hidden_states, attention_mask=None):
        mixed_query_layer = self.query(hidden_states)
        mixed_key_layer = self.key(hidden_states)
        mixed_value_layer = self.value(hidden_states)

        query_layer = self.transpose_for_scores(mixed_query_layer)
        key_layer = self.transpose_for_scores(mixed_key_layer)
        value_layer = self.transpose_for_scores(mixed_value_layer)

        # 计算注意力分数
        attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
        attention_scores = attention_scores / torch.sqrt(torch.tensor(self.attention_head_size, dtype=torch.float32))
        
        if attention_mask is not None:
            attention_scores = attention_scores + attention_mask

        # 归一化得到注意力权重
        attention_probs = nn.Softmax(dim=-1)(attention_scores)
        attention_probs = self.dropout(attention_probs)

        # 加权求和
        context_layer = torch.matmul(attention_probs, value_layer)
        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(*new_context_layer_shape)
        
        return context_layer

自注意力计算流程:

  1. 线性变换生成Q、K、V矩阵
  2. 计算QK^T得到注意力分数
  3. 缩放点积并应用注意力掩码
  4. Softmax归一化得到注意力权重
  5. 加权求和得到上下文表示

2.2 层归一化与残差连接

BERT在每个子层(自注意力、前馈网络)后都使用残差连接(Residual Connection)和层归一化(Layer Normalization):

# 残差连接与层归一化组合实现
class BertLayer(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.attention = BertSelfAttention(config)
        self.attention_output = BertSelfOutput(config)  # 包含LayerNorm和残差
        self.intermediate = BertIntermediate(config)
        self.output = BertOutput(config)  # 包含LayerNorm和残差

    def forward(self, hidden_states, attention_mask=None):
        # 自注意力子层
        self_attention_outputs = self.attention(hidden_states, attention_mask)
        attention_output = self.attention_output(self_attention_outputs[0], hidden_states)
        
        # 前馈网络子层
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        
        return layer_output

# 简化版LayerNorm实现
class BertLayerNorm(nn.Module):
    def __init__(self, hidden_size, eps=1e-5):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(hidden_size))
        self.bias = nn.Parameter(torch.zeros(hidden_size))
        self.variance_epsilon = eps

    def forward(self, x):
        u = x.mean(-1, keepdim=True)
        s = (x - u).pow(2).mean(-1, keepdim=True)
        x = (x - u) / torch.sqrt(s + self.variance_epsilon)
        return self.weight * x + self.bias

2.3 位置编码实现

BERT使用可学习的位置嵌入(Learnable Position Embeddings)替代Transformer原始的正弦位置编码:

# 位置嵌入初始化(HuggingFace实现)
def _init_position_embeddings(module, n_positions, hidden_size):
    """初始化位置嵌入矩阵"""
    nn.init.normal_(module.weight, std=0.02)
    # 确保位置嵌入不超过n_positions
    if n_positions is not None and module.weight.size(0) > n_positions:
        module.weight.data[n_positions:, :] = 0

与正弦位置编码的对比:

特性 可学习位置嵌入 正弦位置编码
灵活性 可适应不同任务 固定模式
泛化性 依赖训练数据 天然外推能力
实现复杂度 简单 需手动计算
参数数量 增加 无增加

本节小结

  • 多头注意力通过并行计算提升效率
  • 残差连接+层归一化解决梯度消失问题
  • BERT采用可学习的位置嵌入方案

第三章 训练与微调代码分析

3.1 预训练代码

BERT的预训练包含两个任务:

  1. Masked Language Model (MLM):随机遮盖15%的token进行预测
  2. Next Sentence Prediction (NSP):预测两句话是否连续
# MLM任务实现示例
def mask_tokens(inputs, tokenizer, mlm_probability=0.15):
    """准备masked tokens输入/labels"""
    labels = inputs.clone()
    probability_matrix = torch.full(labels.shape, mlm_probability)
    
    # 特殊token不mask
    special_tokens_mask = [
        tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) 
        for val in labels.tolist()
    ]
    probability_matrix.masked_fill_(torch.tensor(special_tokens_mask, dtype=torch.bool), value=0.0)
    
    masked_indices = torch.bernoulli(probability_matrix).bool()
    labels[~masked_indices] = -100  # 只计算masked位置的loss
    
    # 80%替换为[MASK],10%随机替换,10%保持不变
    indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
    inputs[indices_replaced] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token)
    
    indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
    random_words = torch.randint(len(tokenizer), labels.shape, dtype=torch.long)
    inputs[indices_random] = random_words[indices_random]
    
    return inputs, labels

3.2 微调代码

以文本分类任务为例的微调流程:

from transformers import BertForSequenceClassification, BertTokenizer
import torch

# 加载预训练模型和tokenizer
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

# 准备输入数据
text = "This is a positive example."
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)

# 微调训练循环示例
def fine_tune(model, train_loader, epochs=3, lr=2e-5):
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model.to(device)
    
    for epoch in range(epochs):
        model.train()
        for batch in train_loader:
            optimizer.zero_grad()
            batch = {k: v.to(device) for k, v in batch.items()}
            outputs = model(**batch)
            loss = outputs.loss
            loss.backward()
            optimizer.step()

本节小结

  • 预训练通过MLM和NSP任务学习通用表示
  • 微调只需在预训练模型上添加简单分类层
  • 不同任务需调整输入输出处理逻辑

课程总结

本课程通过解析BERT源码,深入讲解了Transformer的核心实现细节:

  1. 架构理解:掌握了BERT的整体架构和输入表示方法
  2. 核心组件:实现了自注意力计算、层归一化和残差连接
  3. 训练流程:分析了预训练和微调的代码实现

建议学员进一步实践:

  1. 在Colab中运行完整BERT训练代码
  2. 尝试修改位置编码方案观察效果变化
  3. 基于本课程实现一个简化版Transformer模型
广告位 300x250 正文内嵌广告3 ¥600/月
广告位 320x50 手机底部粘性广告 ¥400/月