Transformer 是 2017 年提出的革命性架构,完全摒弃了 RNN/CNN,仅使用注意力机制(Attention)就在机器翻译、文本理解等任务上取得了突破性成果。它是现代大语言模型(LLM)的基础。
注意力权重:值越大 = 两个词关系越密切
多个注意力头并行关注不同类型的关系
# Transformer 自注意力机制简化实现
import torch
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.d_model = d_model
self.n_heads = n_heads
self.d_k = d_model // n_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)
def forward(self, x, mask=None):
batch_size = x.size(0)
# 投影并分头
Q = self.W_q(x).view(batch_size, -1, self.n_heads, self.d_k).transpose(1,2)
K = self.W_k(x).view(batch_size, -1, self.n_heads, self.d_k).transpose(1,2)
V = self.W_v(x).view(batch_size, -1, self.n_heads, self.d_k).transpose(1,2)
# 计算注意力分数
scores = torch.matmul(Q, K.transpose(-2,-1)) / math.sqrt(self.d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
attention_output = torch.matmul(attention_weights, V)
# 合并多头并输出
output = attention_output.transpose(1,2).contiguous().view(batch_size, -1, self.d_model)
return self.W_o(output)
Transformer 在不同类型的任务和数据上有广泛应用,了解这些对应关系有助于理解 AI 安全中的攻击面。
BERT(Bidirectional Encoder Representations from Transformers)是 2018 年提出的双向预训练语言模型,在多项 NLP 基准测试中刷新纪录。其核心创新是"双向"和"掩码语言模型"。
# BERT 预训练示例(简化)
from transformers import BertModel, BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
# MLM 预训练
text = "The [MASK] chases the dog."
inputs = tokenizer(text, return_tensors='pt')
outputs = model(**inputs)
predictions = outputs.logits
# 预测被mask的词
mask_token_id = tokenizer.mask_token_id
predicted_id = predictions[0, mask_token_idx].argmax(-1)
predicted_word = tokenizer.decode(predicted_id)
BERT 微调是将预训练模型适配到下游任务的关键步骤,只需要少量标注数据即可取得好效果。
# BERT 分类任务微调示例
from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained(
'bert-base-uncased',
num_labels=2 # 二分类
)
# 训练
outputs = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
loss = outputs.loss
loss.backward()
# 使用 AdamW 优化器,学习率2e-5
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)
基于 Transformer 和 BERT 的架构改进,衍生出众多影响力深远的模型。