ARTICLE · 1436318
200行代码看懂GPT本质

AI 大神 Andrej Karpathy 又放大招了!用约 200 行纯 Python 代码,从零实现了一个可训练、可推理的 GPT 模型。文件叫 microgpt.py,几乎没有第三方依赖。
Karpathy 自己说这是"GPT 的原子级实现"——代码里是算法本身,其他都是效率优化。
项目地址(直接复制打开就能看到完整代码): https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95
代码可以完美分成三栏显示:
第一栏:数据集 + 分词器 + 微型自动求导引擎 第二栏:GPT 模型本体 第三栏:训练循环 + 推理生成
这简直是数学与工程美学的极致碰撞。下面我们来拆解这个项目为什么这么炸裂,用四个关键亮点来 说清楚。
一、 亮点一:极致简洁,约 200 行就是 GPT 的全部算法
很多人看到大模型几万几十万行代码,会觉得 LLM 很复杂。Karpathy 证明了:GPT 的核心算法其实很短。
在这个microgpt里,你能看到完整的:
字符级 Tokenizer(带 BOS/EOS 特殊 token) 词表嵌入 + 位置嵌入(weight tying:输出层复用词表嵌入) 多头自注意力(包括 QKV 投影、softmax attention) RMSNorm 层归一化 Squared ReLU 激活的前馈网络(MLP) 残差连接 交叉熵损失 手写 Adam 优化器 + 学习率线性衰减 前向传播、反向传播(逐 token backward)、参数更新 自回归采样推理
全部塞进约 200 行,没有一行是废话,没有一个多余的抽象,每一行都在做 GPT 必须的数学运算。
二、 亮点二:零依赖实现,纯Python手写,没有任何第三方库
代码只用了 Python 标准库:os、math、random、argparse,以及按需下载数据集时才用 urllib:
import os # for os.path.exists import math # for math.log, math.exp import random # for random.seed, random.choices import argparse # for argparse.ArgumentParser没有 NumPy,没有 PyTorch,没有 TensorFlow,甚至连 collections、typing 这些常用模块都没引入。
所有的矩阵乘法、softmax、层归一化、Adam 动量,都是用最原始的 for 循环 + 列表 + 基本数学运算手写出来的。
这带来的好处是:你真正能看懂每一行代码在干什么。没有黑盒调用,没有框架魔法。你可以一行一 行跟踪数据是怎么流动、梯度是怎么传播的。
对想真正搞懂 Transformer 的人来说,这是目前最透明化的实现之一。
三、 亮点三:教育价值巨大,把 LLM 从黑盒变成了玻璃盒
过去几年,大家用 PyTorch、HuggingFace、vLLM 等框架训练/微调大模型,但真正理解"它为什么能工作"的越来越少。
Karpathy 的这一波操作,直接把 LLM 剥到最里面一层:
原来注意力就是几个矩阵乘 + softmax + 加权求和 原来前馈网络就是两层线性 + Squared ReLU 原来优化就是对每个参数做加减乘除 原来自动求导也可以用极简的 autograd 引擎实现(基于 _backward 闭包 + 链式法则)

模型参数初始化,用嵌套列表存储矩阵(注意使用了 weight tying,没有独立的 lm_head):
# CLI arguments parser = argparse.ArgumentParser() parser.add_argument('--n_embd', type=int, default=16) parser.add_argument('--n_layer', type=int, default=1) parser.add_argument('--block_size', type=int, default=8) parser.add_argument('--num_steps', type=int, default=1000) parser.add_argument('--n_head', type=int, default=4) parser.add_argument('--learning_rate', type=float, default=1e-2) parser.add_argument('--seed', type=int, default=42) args = parser.parse_args() random.seed(args.seed) n_embd, block_size, n_layer, n_head = args.n_embd, args.block_size, args.n_layer, args.n_head head_dim = n_embd // n_head # Model parameter initialization matrix = lambda nout, nin, std=0.02: [ [Value(random.gauss(0, std)) for _ in range(nin)] for _ in range(nout) ] state_dict = {'wte': matrix(vocab_size, n_embd), 'wpe': matrix(block_size, n_embd)} for i in range(n_layer): state_dict[f'layer{i}.attn_wq'] = matrix(n_embd, n_embd) state_dict[f'layer{i}.attn_wk'] = matrix(n_embd, n_embd) state_dict[f'layer{i}.attn_wv'] = matrix(n_embd, n_embd) state_dict[f'layer{i}.attn_wo'] = matrix(n_embd, n_embd, std=0) state_dict[f'layer{i}.mlp_fc1'] = matrix(4 * n_embd, n_embd) state_dict[f'layer{i}.mlp_fc2'] = matrix(n_embd, 4 * n_embd, std=0) params = [p for mat in state_dict.values() for row in mat for p in row]核心的 GPT 函数,包含完整的注意力机制:
def gpt(token_id, pos_id, keys, values): tok_emb = state_dict['wte'][token_id] # token embedding pos_emb = state_dict['wpe'][pos_id] # position embedding x = [t + p for t, p in zip(tok_emb, pos_emb)] # joint token and position embedding x = rmsnorm(x)for li in range(n_layer):# 1) Multi-head attention block x_residual = x x = rmsnorm(x) q = linear(x, state_dict[f'layer{li}.attn_wq']) k = linear(x, state_dict[f'layer{li}.attn_wk']) v = linear(x, state_dict[f'layer{li}.attn_wv']) keys[li].append(k) values[li].append(v) x_attn = []for h in range(n_head): hs = h * head_dim q_h = q[hs:hs+head_dim] k_h = [ki[hs:hs+head_dim] for ki in keys[li]] v_h = [vi[hs:hs+head_dim] for vi in values[li]] attn_logits = [sum(q_h[j] * k_h[t][j] for j in range(head_dim)) / head_dim**0.5 for t in range(len(k_h))] attn_weights = softmax(attn_logits) head_out = [sum(attn_weights[t] * v_h[t][j] for t in range(len(v_h))) for j in range(head_dim)] x_attn.extend(head_out) x = linear(x_attn, state_dict[f'layer{li}.attn_wo']) x = [a + b for a, b in zip(x, x_residual)]# 2) MLP block x_residual = x x = rmsnorm(x) x = linear(x, state_dict[f'layer{li}.mlp_fc1']) x = [xi.relu() for xi in x] x = linear(x, state_dict[f'layer{li}.mlp_fc2']) x = [a + b for a, b in zip(x, x_residual)] logits = linear(x, state_dict['lm_head'])return logits辅助函数都是最基础的实现:
# Define the model architecture: a stateless function mapping token sequence and parameters to logits over what comes next.# Follow GPT-2, blessed among the GPTs, with minor differences: layernorm -> rmsnorm, no biases, GeLU -> ReLUdef linear(x, w):return [sum(wi * xi for wi, xi in zip(wo, x)) for wo in w]def softmax(logits): max_val = max(val.data for val in logits) exps = [(val - max_val).exp() for val in logits] total = sum(exps)return [e / total for e in exps]def rmsnorm(x): ms = sum(xi * xi for xi in x) / len(x) scale = (ms + 1e-5) ** -0.5return [xi * scale for xi in x]四、 亮点四:自动求导,40行的计算图引擎
整个模型的 forward 和 backward,全靠五个基本操作:加法 +、乘法 *、幂运算 **、对数 log、指数 exp,再加上 ReLU(max(0,x))和 softmax(exp 后归一)。

Karpathy 用一个 Value 类(源自 micrograd)构建计算图,每个操作通过 _backward 闭包记录局部偏导。与文章旧版的 _local_grads 元组方式不同,这里使用的是更经典的闭包 + _prev 集合的设计:
# Let there be Autograd, to recursively apply the chain rule through a computation graphclass Value: __slots__ = ('data', 'grad', '_children', '_local_grads') # Python optimization for memory usage def __init__(self, data, children=(), local_grads=()): self.data = data # scalar value of this node calculated during forward pass self.grad = 0 # derivative of the loss w.r.t. this node, calculated in backward pass self._children = children # children of this node in the computation graph self._local_grads = local_grads # local derivative of this node w.r.t. its children def __add__(self, other): other = other if isinstance(other, Value) else Value(other)return Value(self.data + other.data, (self, other), (1, 1)) def __mul__(self, other): other = other if isinstance(other, Value) else Value(other)return Value(self.data * other.data, (self, other), (other.data, self.data)) def __pow__(self, other): return Value(self.data**other, (self,), (other * self.data**(other-1),)) def log(self): return Value(math.log(self.data), (self,), (1/self.data,)) def exp(self): return Value(math.exp(self.data), (self,), (math.exp(self.data),)) def relu(self): return Value(max(0, self.data), (self,), (float(self.data > 0),)) def __neg__(self): return self * -1 def __radd__(self, other): return self + other def __sub__(self, other): return self + (-other) def __rsub__(self, other): return other + (-self) def __rmul__(self, other): return self * other def __truediv__(self, other): return self * other**-1 def __rtruediv__(self, other): return other * self**-1 def backward(self): topo = [] visited = set() def build_topo(v):if v not in visited: visited.add(v)for child in v._children: build_topo(child) topo.append(v) build_topo(self) self.grad = 1for v in reversed(topo):for child, local_grad in zip(v._children, v._local_grads): child.grad += local_grad * v.grad核心思想:每个操作通过闭包捕获局部梯度计算逻辑,backward() 时按拓扑排序依次调用 _backward() 闭包,通过链式法则传播梯度。
五、 训练循环:逐 token 反向传播 + 手写 Adam 优化器

与常见的"收集所有 loss 再统一 backward"不同,microgpt 采用逐 token backward 的方式,每个位置独立计算 loss 并反向传播:
# Let there be Adam, the blessed optimizer and its bufferslearning_rate, beta1, beta2, eps_adam = 0.01, 0.85, 0.99, 1e-8m = [0.0] * len(params) # first moment bufferv = [0.0] * len(params) # second moment buffer# Repeat in sequencenum_steps = 1000 # number of training stepsfor step in range(num_steps):# Take single document, tokenize it, surround it with BOS special token on both sides doc = docs[step % len(docs)] tokens = [BOS] + [uchars.index(ch) for ch in doc] + [BOS] n = min(block_size, len(tokens) - 1)# Forward the token sequence through the model, building up the computation graph all the way to the loss. keys, values = [[] for _ in range(n_layer)], [[] for _ in range(n_layer)] losses = []for pos_id in range(n): token_id, target_id = tokens[pos_id], tokens[pos_id + 1] logits = gpt(token_id, pos_id, keys, values) probs = softmax(logits) loss_t = -probs[target_id].log() losses.append(loss_t) loss = (1 / n) * sum(losses) # final average loss over the document sequence. May yours be low.# Backward the loss, calculating the gradients with respect to all model parameters. loss.backward()# Adam optimizer update: update the model parameters based on the corresponding gradients. lr_t = learning_rate * (1 - step / num_steps) # linear learning rate decayfor i, p in enumerate(params): m[i] = beta1 * m[i] + (1 - beta1) * p.grad v[i] = beta2 * v[i] + (1 - beta2) * p.grad ** 2 m_hat = m[i] / (1 - beta1 ** (step + 1)) v_hat = v[i] / (1 - beta2 ** (step + 1)) p.data -= lr_t * m_hat / (v_hat ** 0.5 + eps_adam) p.grad = 0print(f"step {step+1:4d} / {num_steps:4d} | loss {loss.data:.4f}")六、 推理生成
推理阶段使用自回归采样,直接基于 softmax 概率分布进行采样(原始代码未使用 temperature 参数):
# Inference: may the model babble back to ustemperature = 0.5 # in (0, 1], control the "creativity" of generated text, low to highprint("\n--- inference (new, hallucinated names) ---")for sample_idx in range(20): keys, values = [[] for _ in range(n_layer)], [[] for _ in range(n_layer)] token_id = BOS sample = []for pos_id in range(block_size): logits = gpt(token_id, pos_id, keys, values) probs = softmax([l / temperature for l in logits]) token_id = random.choices(range(vocab_size), weights=[p.data for p in probs])[0]if token_id == BOS:break sample.append(uchars[token_id])print(f"sample {sample_idx+1:2d}: {''.join(sample)}")七、与旧版(243 行)的关键差异
Karpathy 在精简过程中做了以下关键改动:
Value 类:从 slots + _local_grads 元组风格,改为更经典的 _backward 闭包 + _prev 集合设计 Weight Tying:移除了独立的 lm_head,输出层直接复用 wte 嵌入矩阵 Squared ReLU:从普通 ReLU 改为 xi.relu() ** 2 Tokenizer:使用 BOS 和 EOS 两个特殊 token,而非单一的 BOS 训练方式:逐 token backward,而非收集所有 loss 后统一 backward Adam 超参数:beta1=0.9, beta2=0.95(更接近 GPT 标准配置) 参数初始化:std=0.02(更标准),且部分层使用 std=0(如 attn_wo, mlp_fc2) CLI 支持:通过 argparse 支持命令行配置超参数 默认 block_size:从 16 改为 8
八、 结语
当 ChatGPT变成日常工具,当百模大战和参数竞赛成为主旋律,Karpathy 把问题拉回原点:大模型到底是什么?它最干净的样子长什么样?
microgpt.py 给出了答案:约 200 行纯 Python,就是 GPT 的全部灵魂。
建议每一个对 LLM 原理感兴趣的朋友,都去把这个 gist 点开,慢慢读一遍代码,哪怕只读懂一半,你对 Transformer 和语言模型的理解都会上一个大台阶。
代码链接再放一次(直接点开就能复制运行): https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95















































































