Ainsteinx Logo
Ainsteinx
👤
欢迎使用 Ainsteinx
登录

切换语言

货币

首页
博客
服务
第 09 课 · 应用

Transformer 与 GPT

注意力机制:让每个词自己决定该关注哪些词。

Transformer 用自注意力取代 LSTM:每个 token 生成 query、key 和 value,并按 query 与 key 的相似度给其他 token 分配权重。GPT 是带因果掩码的 Transformer,因此能预测下一个词。

示例计算 4 个词的注意力并打印权重表——右上三角全为 0,因为掩码禁止看到未来。

Attention(Q, K, V) = softmax( Q·Kᵀ / √d + mask ) · V mask[i, j] = −∞ 当 j > i
模块作用
Multi-head attention多个头同时关注不同的关系
Positional encoding告诉模型 token 的顺序
层归一化 + 残差连接让多层堆叠保持稳定
Encoder / DecoderBERT = 编码器,GPT = 解码器,T5 = 两者都有

要点

  • 注意力同时看到所有词,所以能并行训练并处理长上下文
  • ChatGPT 就是大型 GPT + 指令微调(RLHF)
generative-ai-ep09-transformers.py
import torch

torch.manual_seed(0)
tokens = ["the", "cat", "sat", "down"]
d = 8
x = torch.randn(len(tokens), d)                      # token embeddings
Wq, Wk, Wv = (torch.randn(d, d) / d ** 0.5 for _ in range(3))
Q, K, V = x @ Wq, x @ Wk, x @ Wv

scores = Q @ K.T / d ** 0.5                          # how much each token looks at each other
mask = torch.triu(torch.ones(len(tokens), len(tokens)), diagonal=1).bool()
scores = scores.masked_fill(mask, float("-inf"))     # causal mask: no peeking at the future
weights = torch.softmax(scores, dim=-1)
out = weights @ V

print("attention weights (row = query token):")
print("      " + "".join(f"{t:>7}" for t in tokens))
for t, row in zip(tokens, weights):
    print(f"{t:>6}" + "".join(f"{w:7.2f}" for w in row))
print("output shape:", tuple(out.shape))

输出结果

attention weights (row = query token):
          the    cat    sat   down
   the   1.00   0.00   0.00   0.00
   cat   0.40   0.60   0.00   0.00
   sat   0.38   0.59   0.04   0.00
  down   0.09   0.13   0.68   0.10
output shape: (4, 8)
  • #GenerativeAI
  • #DeepLearning
  • #PythonສຳລັບຄົນLaos
  • #AI
  • #ບອກຕໍ່ຄວາມຮູ້