19
基础与模型
Transformer 基础
怎么学、手写注意力、失败模式、从零资源
训练循环、注意力和因果掩码、LLM 训练三段,加上从零写 GPT 的资源。
我的理解
- 为什么我也要懂:会遇到“长上下文为什么慢”(注意力 O(n²)、KV Cache)、“MoE 为什么便宜”、“推理模型为什么贵”这类问题。
- 训练 = 前向算 loss → 反向算梯度 → 优化器更新,所有模型都一样。
- 注意力:每个 token 用 Q 去和所有 K 比相似度,softmax 后加权求和 V;多头 = 多组并行;除以 √dk 防止分数过大。
- 因果掩码:生成时只能看过去,所以 GPT 能逐 token 生成。
- LLM 三段:预训练(海量文本)→ SFT(指令数据)→ 偏好对齐(RLHF / DPO / GRPO)。
- GQA vs MLA(Raschka 架构对比):GQA 让多个 query head 共享一组 K/V,减少 K/V 头数,省参数和 KV cache 带宽;MLA(DeepSeek-V2 引入,V3 沿用)把 K/V 压缩到低维再存进 KV cache,推理时多一次矩阵乘投影回去。DeepSeek-V2 论文的消融里 MLA 略好于 MHA、GQA 略差于 MHA。
- MoE:FFN 换成多个 expert,每个 token 只激活少数几个(稀疏)。Raschka 举的例子:DeepSeek V3 每个 MoE 模块 256 个 expert、总参数 671B,推理时只激活 9 个(1 个 shared expert + router 选的 8 个),每步约 37B 参数。shared expert 对每个 token 都激活,学共性模式。
- 同一篇里还有:QK-Norm(在 attention 里对 q、k 再做一次 RMSNorm,放在 RoPE 之前,OLMo 2 / Gemma 用)、滑动窗口注意力(Gemma 3)、NoPE(不用位置编码)。部署时 KV cache 大小就看这些设计,和《部署:本地推理与阿里云》对着看。
- @antiAIvo 的知识地图顺序:Transformer/GPT → Scaling Laws 与并行训练 → LLaMA、RoPE、GQA、MLA → MoE → RLHF、DPO、GRPO、R1 → KV Cache、量化、vLLM → DeepSeek / Qwen / Kimi 技术报告 → Agent、MCP。
代码
最小训练循环(只过了语法检查)
python
# 最小训练循环 —— 5 行核心对所有模型都一样
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(512, 2)
y = (X[:, 0] * X[:, 1] > 0).long() # 异或型数据:线性分不开,MLP 可以
model = nn.Sequential(nn.Linear(2, 32), nn.ReLU(), nn.Linear(32, 2))
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(200):
logits = model(X) # 前向
loss = loss_fn(logits, y) # 损失
opt.zero_grad() # 清梯度
loss.backward() # 反向
opt.step() # 更新
if epoch % 50 == 0:
print(epoch, round(loss.item(), 3), (logits.argmax(1) == y).float().mean().item())
多头因果自注意力(只过了语法检查)
python
# 多头因果自注意力(GPT 核心)
import math, torch
from torch import nn
import torch.nn.functional as F
class CausalSelfAttention(nn.Module):
def __init__(self, d_model: int = 64, n_heads: int = 4):
super().__init__()
assert d_model % n_heads == 0
self.h, self.dk = n_heads, d_model // n_heads
self.qkv = nn.Linear(d_model, 3 * d_model)
self.out = nn.Linear(d_model, d_model)
def forward(self, x): # (B, T, C)
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=-1)
q, k, v = (t.view(B, T, self.h, self.dk).transpose(1, 2) for t in (q, k, v)) # (B,h,T,dk)
scores = q @ k.transpose(-2, -1) / math.sqrt(self.dk) # (B,h,T,T)
mask = torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))
scores = scores.masked_fill(~mask, float("-inf")) # 看不到未来
y = (F.softmax(scores, dim=-1) @ v).transpose(1, 2).contiguous().view(B, T, C)
return self.out(y)
print(CausalSelfAttention()(torch.randn(2, 8, 64)).shape) # 期望 (2, 8, 64)
速记
code
训练:logits=model(x); loss=fn(logits,y); opt.zero_grad(); loss.backward(); opt.step()
怎么学(决策)
| 目标 | 路径 | 别先做 |
|---|---|---|
| 建立直觉 | Karpathy Zero-to-Hero → 自己改超参 | 只收藏不敲 |
| 看懂注意力 | 手写 causal mask;打印 weights | 一上来 Annotated Transformer 全文 |
| 跟现代 LLM | rasbt LLMs-from-scratch / happy-llm | 跳过形状注释直接抄大仓库 |
| 对照架构变体 | Raschka Big LLM Architecture Comparison | 背名词不对照代码 |
| 和应用笔记衔接 | 会解释:为什么长上下文贵、为什么要 KV-cache | 基础和应用两张皮 |
失败模式
| 现象 | 常见原因 | 我怎么处置 |
|---|---|---|
| 看完啥也不会 | 只看视频 | 每集复现;改 hidden 看准确率 |
| loss 对但形状懵 | 没标 (B,T,C) | 每步注释形状 |
| 论文读不进 | 缺代码锚点 | 先 nano/from-scratch 再 Annotated |
踩坑 / 注意
- ❌ 坑:只看视频不敲——每集都自己复现。
- ❌ 坑:张量形状搞混——每一步注释 (B, T, C)。
- ❌ 坑:一上来读论文原文——先读 LLMs-from-scratch / nanochat 的代码,再回头读论文。
待试
- [ ] 训练循环把隐藏层从 32 改成 2,看准确率掉多少
- [ ] 去掉因果掩码,打印 weights[0, 0],看上三角
- [ ] 跟 Karpathy 视频实现 micrograd 和 makemore
收藏
- @antiAIvo:交互式大模型知识地图(8 阶段 51 点)—— 查“我还缺哪块” — x.com
- nano-ai.tech 知识地图本体 — nano-ai.tech
- @rasbt:LLMs-from-scratch 突破 10 万星 —— 从零写 GPT 的首选 — x.com
- rasbt/LLMs-from-scratch — github.com
- @akshay_pachaar:Karpathy nanochat —— 分词器 → 预训练 → SFT → 评估一整条小流水线 — x.com
- karpathy/nanochat — github.com
- Karpathy:Neural Networks: Zero to Hero —— micrograd / makemore — karpathy.ai
- Zero to Hero 播放列表 — YouTube
- 3Blue1Brown 神经网络 / LLM 可视化 —— 先建立直觉 — YouTube
- @GoSailGlobal:Google 免费 AI 课程(含注意力机制) — x.com
- Datawhale happy-llm —— 中文从零理解大模型 — github.com
- dive-into-llms —— 中文动手学大模型 — github.com
- 《动手学深度学习》中文版 —— 数学附录查漏 — zh.d2l.ai
- Hugging Face LLM 课程 — huggingface.co
- fast.ai 实用深度学习 — course.fast.ai
- Sebastian Raschka:The Big LLM Architecture Comparison —— MLA / MoE / QK-Norm / 滑动窗口逐个模型对比 — magazine.sebastianraschka.com
- Jay Alammar:The Illustrated Transformer —— 图解,先建立直觉 — jalammar.github.io
- The Annotated Transformer(Harvard NLP)—— 论文逐段配 PyTorch 代码 — nlp.seas.harvard.edu
更多收藏
- raw 里的精确链接:LLMs-from-scratch README https://raw.githubusercontent.com/rasbt/LLMs-from-scratch/main/README.md ;Datawhale happy-llm README https://raw.githubusercontent.com/datawhalechina/happy-llm/main/README.md ;@rasbt 从零写 LLM 系列的分词视频 https://x.com/rasbt/status/1896208257884066027
- MoE / DeepSeek:@cwolferesearch nanoMoE(约 500 行,作者说普通硬件一周内可预训练)https://x.com/cwolferesearch/status/1899172553626685532 ;@_avichawla Transformer vs MoE 图解 https://x.com/_avichawla/status/1894273625681007010 ;@Hesamation MoE 图解(只有图)https://x.com/Hesamation/status/1923805227913826711 、DeepSeek R1 长文导读 https://x.com/Hesamation/status/1884532647054987490 、DeepSeek by hand https://x.com/Hesamation/status/1887844757403034087 、16 小时从零写 DeepSeek https://x.com/Hesamation/status/1987308127579218188
- 课程:@Hesamation 斯坦福 Transformers & LLMs 课 https://x.com/Hesamation/status/1979606021636014363 ;@GitHub_Daily 斯坦福 CME 295 https://x.com/GitHub_Daily/status/1985889897862086671 ;@akshay_pachaar 交互式看 Transformer 内部(视频)https://x.com/akshay_pachaar/status/1906323086586388502 ;@Barret_China《图解大模型》https://x.com/Barret_China/status/1973281105500577889
- @dotey 杨植麟 GTC 2026《How We Scaled Kimi K2.5》摘要 https://x.com/dotey/status/2078172517085085951 —— 转述,具体技术细节待核对
- 上面收藏里 @antiAIvo、@rasbt 10 万星、@akshay_pachaar nanochat、@GoSailGlobal 这几条来自旧草稿,raw 里没有。