5Combine: x = tok_emb + pos_emb
Content (step 3) + Position (step 4), added elementwise, same shape — real numbers spelled out on the right, no arrow needed to "prove" it
x = tok_emb + pos_emb # (B,T,C) + (T,C) broadcasts over B
(B,T,64) + (T,64) → (B,T,64)
Every position's vector now carries both "what token" and "where in the sequence" information, fused by simple addition. This is the actual input to the first Block — q = self.query(x) later means this x, not the raw token embedding alone.
full source — BigramLanguageModel.forward() (gpt-dev.ipynb)same class as steps 3 & 4
def forward(self, idx, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx) # (B,T,C)
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
x = tok_emb + pos_emb # (B,T,C)
x = self.blocks(x) # (B,T,C)
x = self.ln_f(x) # (B,T,C)
logits = self.lm_head(x) # (B,T,vocab_size)
PyTorch internals:
+ on two tensors calls torch.Tensor.__add__, which dispatches to torch.add — an elementwise kernel. Because pos_emb is shape (T,C) and tok_emb is (B,T,C), PyTorch broadcasts by treating the missing leading dimension as size 1 and repeating it — no memory is actually duplicated B times for pos_emb, the broadcast is virtual until the addition materializes the output.📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell 8119b626
class BigramLanguageModel(nn.Module): def __init__(self): super().__init__() # each token directly reads off the logits for the next token from a lookup table # 将vocab_size个字符映射到n_embd维的向量空间中 # 输入xb和yb是形状为(B,T)的整数张量,输出是形状为(B,T,C)的浮点数张量,其中C是内部的维度n_embd self.token_embedding_table = nn.Embedding(vocab_size, n_embd) # 位置向量的计算基于sequence的长度T,所以输入是一个长度为T的整数张量,输出是一个形状为(T,C)的浮点数张量 self.position_embedding_table = nn.Embedding(block_size, n_embd) # 因为作为基本transformer单元的Block输出形状是B,T,n_embd,所以输入也是B,T,n_embd,输出也是B,T,n_embd self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)]) self.ln_f = nn.LayerNorm(n_embd) # final layer norm # 将B,T,n_embd维的表示映射回vocab_size维的空间中,得到每个位置上每个字符的预测分数,变成B,T,vocab_size的形状 self.lm_head = nn.Linear(n_embd, vocab_size) def forward(self, idx, targets=None): B, T = idx.shape # idx and targets are both (B,T) tensor of integers,we pass them through the model to produce logits, which are (B,T,vocab_size) tensor of floats # 输入来自xb和yb是形状为(B,T)的整数张量 tok_emb = self.token_embedding_table(idx) # (B,T,C) pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C) # 这里的广播机制会将pos_emb从(T,C)扩展到(B,T,C),使得每个序列位置都有一个对应的嵌入向量 x = tok_emb + pos_emb # (B,T,C) x = self.blocks(x) # (B,T,C) 之前被误注释掉,导致 attention/FFN 完全不生效,这里改正 x = self.ln_f(x) # (B,T,C) logits = self.lm_head(x) # (B,T,vocab_size) if targets is None: loss = None else: B, T, C = logits.shape logits = logits.view(B*T, C) targets = targets.view(B*T) loss = F.cross_entropy(logits, targets) return logits, loss # generate def generate(self, idx, max_new_tokens): # idx is (B, T) array of indices in the current context for _ in range(max_new_tokens): # crop idx to the last block_size tokens idx_cond = idx[:, -block_size:] # get the predictions logits, loss = self(idx_cond) # focus only on the last time step logits = logits[:, -1, :] # becomes (B, C) # apply softmax to get probabilities probs = F.softmax(logits, dim=-1) # (B, C) # sample from the distribution idx_next = torch.multinomial(probs, num_samples=1) # (B, 1) # append sampled index to the running sequence idx = torch.cat((idx, idx_next), dim=1) # (B, T+1) return idx
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note 24747ec1
术语校正:batch 维度是"批量矩阵乘法",不是"广播"
推演 q @ k.transpose(-2,-1) 时容易脱口而出"广播到 batch",但这个词用得不准确,需要和"广播(broadcast)"严格区分开:
广播(broadcast)—— 本 notebook 里真正的例子:
pos_emb: (T, C) 本身没有 B 维
tok_emb: (B, T, C)
x = tok_emb + pos_emb
→ pos_emb 被"虚拟复制"到每个 batch,用的是同一份数值
批量矩阵乘法(batched matmul)—— q @ k.transpose(-2,-1) 真正在做的事:
q: (B, T, head_size),k.T: (B, head_size, T)
每个 batch 元素 b 的 q[b]、k[b] 数值都不同(来自不同的输入序列)
PyTorch 对 3D 张量的 @ 运算符,是对每个 b 独立做一次 q[b] @ k[b].T(标准 2D 矩阵乘法)
只是把 B 次独立运算打包成一次调用,不是把"同一个结果"复制给所有 batch
一句话区分:广播是"没有的维度,靠复制凑出来";批量矩阵乘法是"每个 batch 都有自己独立的数据,各算各的,只是循环被打包成一次调用"。 这也是为什么"batch 之间永远独立"成立——独立的原因不是"没算过",而是"每个 batch 都用自己的数据单独算了一遍"。
再精确一处:wei = q@k.T 和 out = wei@v 虽然都叫矩阵乘法,但坍缩的方向不同,不要都笼统叫"点积"
q @ k.transpose(-2,-1): 每个 wei[t,t'] = q[t]·k[t'](head_size 维向量的点积)→ 坍缩成 1 个标量
这一步严格来说是"点积":把一个向量压缩成一个数
wei @ v: 每个 out[t] = Σ_t' wei[t,t'] · v[t'](标量加权 + 向量求和)→ 结果仍是 head_size 维向量
这一步更准确叫"加权求和":把多个向量按权重合并成一个新向量,不会坍缩成标量
用"点积"统一描述这两步,容易掩盖"一个坍缩成标量、一个仍是向量"这个关键差异。