Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析

2026 年 2 月,Karpathy 发布了 microgpt ------ 200 行纯 Python、零依赖的 GPT 实现。
包含全部核心算法:Tokenizer、Autograd、Transformer、Adam、训练+推理。
"This file is the complete algorithm. Everything else is just efficiency." --- Karpathy
为什么重要?
- 零依赖:只要标准库
- 完整实现:一气呵成
- 200 行:一周能吃透

核心模块
Tokenizer
python
uchars = sorted(set(''.join(docs)))
BOS = len(uchars)
Autograd
python
class Value:
def __init__(self, data):
self.data = data
self.grad = 0.0
Transformer
python
class Attention:
def __call__(self, x):
q = x @ self.wq
att = q @ k.T / math.sqrt(self.head_size)
return softmax(att) @ v
