1Raw text → Tokenizer → Token IDs
stoi = {ch:i for i,ch in enumerate(chars)}
data = torch.tensor(encode(text), dtype=torch.long)
Every character in your 1.1M-character dataset gets replaced by its integer id from a fixed 65-character vocabulary. This is 1D — one giant flat list, no batch or sequence grouping yet.
# here are all the unique characters that occur in this text chars = sorted(list(set(text))) vocab_size = len(chars) # create a mapping from characters to integers stoi = { ch:i for i,ch in enumerate(chars) } itos = { i:ch for i,ch in enumerate(chars) } encode = lambda s: [stoi[c] for c in s] # encoder: string -> list of ints decode = lambda l: ''.join([itos[i] for i in l]) # decoder: list of ints -> string # let's now encode the entire text dataset and store it into a torch.Tensor data = torch.tensor(encode(text), dtype=torch.long) # split into train/val — used by get_batch() in the next step n = int(0.9*len(data)) train_data = data[:n] val_data = data[n:]
stoi/itos are plain Python dicts, encode/decode are plain Python list comprehensions. The only PyTorch call is torch.tensor(...), which just copies the Python list into a contiguous int64 array.📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell d6753cbc
# here are all the unique characters that occur in this text chars = sorted(list(set(text))) vocab_size = len(chars) print(''.join(chars)) print(vocab_size)
cell b8e70e1f
# create a mapping from characters to integers stoi = { ch:i for i,ch in enumerate(chars) } itos = { i:ch for i,ch in enumerate(chars) } encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string print(encode("hii there")) print(decode(encode("hii there")))
cell 9554e929
# let's now encode the entire text dataset and store it into a torch.Tensor import torch # we use PyTorch: https://pytorch.org data = torch.tensor(encode(text), dtype=torch.long) print(len(data)) print(data.shape, data.dtype) print(data[:1000]) # the 1000 characters we looked at earier will to the GPT look like this
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note d1a51b2b
五个核心问题
Q1: 1D / 2D / 3D — 是真实的数据形状,不是比喻
原始文本 "First Citizen:\nBefore..."
↓ encode()
1D tensor: [18, 47, 56, 57, 58, ...], shape=(1115394,) ← 真实的,就是全部 token
↓ get_batch()
2D tensor: shape=(B, T) = (16, 32) ← B 行独立序列,每行 T 个 token ID
↓ token_embedding_table(x)
3D tensor: shape=(B, T, n_embd) = (16, 32, 64) ← 每个 token ID 扩展成 n_embd 维向量
Q2: Causal Mask — 什么时候必须用,什么时候不需要(容易被简化过头的一点)
训练时:整个序列 (B, T) 并行喂入模型,mask 让位置 t 只能看 0..t(含它自己),防止"作弊"看到未来。
推理时要分两种情况,不能一概而论:
| 场景 | 一次前向传播里同时存在几个 query 位置? | 需要显式 causal mask 吗? | 原因 |
|---|---|---|---|
| prefill(处理 prompt,P 个 token 并行喂入) | P 个(多个位置同时算 attention) | 需要 | 和训练一样,多个位置互相看得见,必须显式挡住"看未来" |
| incremental decode(用 KV Cache,每步只喂 1 个新 token) | 1 个(只有当前新 token 在提问) | 不需要 | k_cache/v_cache 里只可能装着"过去和现在"的 K/V,天生不存在"未来"可看,没有东西需要挡 |
一句话记住:"要不要 mask" 的本质不是"训练 vs 推理",而是**"这次前向传播里,是不是有不止一个位置在同时计算 attention"**—— 只要是多位置并行(训练的整个 batch,或推理时的 prefill),就必须显式 mask;只要是单 query 对历史 cache(KV Cache 的增量解码),mask 天然不需要,因为压根没有"未来"存在于 cache 里。
KV Cache 是一个工程优化:缓存已经计算过的 K 和 V 矩阵,避免每一步重复计算。但它有一个常被忽略的副作用——顺便让 mask 变得不必要(因为单 query 场景下没有未来可看)。准确的说法不是"KV Cache 不改变 mask 的必要性",而是KV Cache 恰好改变了要不要 mask 这件事本身。
Q3: Autoregressive — 用自己的输出作为下一步输入,与 KV Cache 无关
"Auto"(自)+ "Regressive"(回归,即用历史预测未来)
# generate() 的本质逻辑:
# step 1: 输入 [t0] → 预测 t1
# step 2: 输入 [t0, t1] → 预测 t2
# step 3: 输入 [t0, t1, t2] → 预测 t3
# ...
每步输出的新 token 追加到序列末尾,成为下一步的输入。这就是"自回归"。 模型本身不变,KV Cache 只是让上面循环更快(复用已算的 K/V),不改变自回归的语义。
Q4: C 的演变路径 — vocab_size → n_embd → vocab_size
输入 x: (B, T) 整数,值域 [0, vocab_size),是 token ID
token_embedding_table: nn.Embedding(vocab_size, n_embd)
= 一张可学习的查找表,形状 (vocab_size, n_embd)
token ID k → 取第 k 行 → n_embd 维向量
经过 embedding 后: (B, T, n_embd) C = n_embd = 64(不是 vocab_size!)
经过若干 Block 变换: (B, T, n_embd) 形状不变,内容被逐步精炼
lm_head: nn.Linear(n_embd, vocab_size)
将每个位置的 n_embd 维向量映射回 vocab_size 维的预测分数
输出 logits: (B, T, vocab_size) C = vocab_size,每个位置上每个字符的原始得分
映射"规则":Embedding 矩阵随机初始化,通过反向传播学习。 训练收敛后,语义相近的 token 在 n_embd 维空间中自然聚集(这是涌现出来的,不是人为设计的)。
Q5: Multi-head — 用多个独立视角同时观察同一个序列
单头的局限:一个 n_embd 维的注意力头,把所有语义关系压缩成一种模式,无法同时学习"语法结构"和"指代关系"等不同维度的依赖。
多头的做法:把 n_embd 切分成 n_head 份,每份(head_size 维)独立计算 attention,最后拼接。
n_embd=64, n_head=4, head_size=16
Head 0: 在 16 维子空间 → 学习某种依赖模式(如短距离语法)
Head 1: 在 16 维子空间 → 学习另一种模式(如指代关系)
Head 2: ...
Head 3: ...
concat: 4 × 16 = 64 维
proj (Linear 64→64): 混合各头信息,输出仍为 n_embd=64
参数总量与单头相同(n_head × head_size = n_embd),但信息被分流到多个独立的注意力视角中并行处理。