4Position Embedding Lookup — a SECOND, separate table

position_embedding_table.weight (32,64) — row 0 (real, since T starts at 0) gathered and broadcast identically into EVERY batch row at t=0, unlike step 3's per-row-different token gather
position_embedding_table = nn.Embedding(block_size, n_embd) pos_emb = position_embedding_table(torch.arange(T))
(T,) → (T, n_embd=64), broadcast over B

A second lookup table, shape (block_size=32, n_embd=64), indexed by position 0..T-1 — not by token id at all. This is why T means two things: "sequence size" (how long is this batch's data) and "position" (which slot, its own identity). Same axis, two angles. The full (32,64) table is drawn on the right, same as step 3's vocab table — the mechanism is identical (one row-gather); only what indexes the row differs (position instead of token id).

Both tables are equally learnable, equally fixed after training — no difference in "fixedness" between them or between W_q/W_k/W_v later. Key contrast with step 3: there, a DIFFERENT row was gathered per batch row (each row = a different token). Here, the SAME row (position 0) is gathered ONCE and broadcast into every batch row at t=0 — pos_emb literally cannot tell batch rows apart, only tok_emb can.
Why token lookup needs 2 coordinates but position lookup needs only 1 — same real data (TOKEN_GRID, step 3), same 3D box style used throughout this page, reduced to just the front face (the true (B,T) surface) so the directional argument is easy to see:
D
                          ╱
                         ╱
            ┌───────────╱───────────┐
           ╱│          ╱           ╱│
          ╱ │         ╱           ╱ │
         ┌───────────┬───────────┐  │
         │ 18 │ 47 │ 56 │ 57 │   │
         ├────┼────┼────┼────┤   │
   B ↓   │ 15 │ 47 │ 58 │ 47 │   ╱
         ├────┼────┼────┼────┤  ╱
         │ 52 │ 10 │  0 │ 14 │ ╱
         └────┴────┴────┴────┘

                 T →

                    T (horizontal) →
              t=0    t=1    t=2    t=3
   b=0    [  18  ] [  47 ] [  56 ] [ 57  ]   ← scan horizontally: token id CHANGES
B  b=1    [  15  ] [  47 ] [  58 ] [ 47  ]      (different char at each position)
(vert.)   [  52  ] [  10 ] [   0 ] [ 14  ]
   ↓
Scan horizontally (fixed b, t increasing): token id changes — and position changes too, both move together. Scan vertically (fixed t, b increasing): token id still changes (18→15→52 — three different real batch rows are three different substrings) — but position does not change; all three cells are still "t=0".

So, precisely: token id = f(b, t) — a function of BOTH surface axes, so it needs a full 2-coordinate gather, a genuinely different row per cell (step 3). position id = f(t) — a function of ONE axis only, provably invariant under the vertical scan — which is exactly why every highlighted cell in the box above shares the identical pos=0 label no matter which batch row it's in, and why the 3 green arrows above all originate from the very same table row.
full source — BigramLanguageModel (gpt-dev.ipynb)__init__ + forward()
class BigramLanguageModel(nn.Module):

    def __init__(self):
        super().__init__()
        self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
        self.position_embedding_table = nn.Embedding(block_size, 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
        self.lm_head = nn.Linear(n_embd, vocab_size)

    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)

        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
PyTorch internals: exactly the same mechanism as step 3's embedding — a second, completely independent (block_size, n_embd) weight matrix. torch.arange(T, device=device) builds the index tensor [0,1,...,T-1] fresh every forward call (it's not learned — only the table's rows are); PyTorch's broadcasting rules then let a (T,C) result be added to a (B,T,C) tensor without you writing any explicit loop over B.

📓 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 219b0ee6

三个后续问题

Q1(原始理解,已修正):不需要 4D 瞬间,本质是二维查表 + 向量化 index

最初的想法:(B,T) 先展开成 one-hot (B,T,vocab_size)("4D 瞬间"),再 @ W 坍缩回 (B,T,n_embd)。

修正后的理解(更准确、更贴近真实实现):

nn.Embedding 的权重 W 本质上只是一张二维表:

W.shape = (vocab_size, n_embd)
            ↑ 行数        ↑ 列数
      由 tokenizer 词表大小唯一决定    架构自由选择的维度,训练前人为设定
      (比如 65 个字符,或 GPT-2 的 50257 个 BPE token)   (不关心具体数值,只是一个"够用"的向量长度)
  • 行:每一行对应一个唯一的 token ID,是身份索引,不可学习(数量由 tokenizer 定死)。
  • 列:随机初始化,训练中被反向传播更新,是"可学习的语义坐标"。
  • 查表 = index:token ID 是几,就直接取第几行,是 O(1) 的 gather 操作。

不需要经过 one-hot 展开再坍缩这一步(那只是数学上等价的另一种表达,PyTorch 底层直接做 weight[input_ids],省掉了构造一个几乎全零的大稀疏张量的开销)。

行数与列数互不耦合:换一个 tokenizer(词表变大/变小)只改变行数,n_embd 完全不受影响——这也印证了"行是身份,列是语义"这个划分是对的。


重要澄清:T 不只是"sequence size",更准确的理解是"position"

这是一个容易卡住理解的地方:

T 这个维度,两种描述都对,但适用场景不同:

"sequence size"  —— 描述的是"这批数据里,一条序列有多长"
                     强调的是数据组织形式(数了多少个 token)

"position"       —— 描述的是"每个 token 在序列中排第几"
                     强调的是每个 token 自己的身份和用途

为什么会同时出现两种叫法:因为 T 这个维度里的每一个元素,来源都是"tokenizer 输出的一个 token ID", 这个 token ID 既承载了内容信息(通过 embedding 查表拿到语义向量),也承载了位置信息(它在序列里排第几,即 position)。

tok_emb = token_embedding_table(idx)                            # 内容:查表得到语义向量
pos_emb = position_embedding_table(torch.arange(T, device=device))  # 位置:0,1,2,...,T-1 这几个位置索引,也去查另一张表
x = tok_emb + pos_emb   # 两者相加,糅合了"内容"和"位置"两种信息

position_embedding_table 是另一张独立的查找表,形状是 (block_size, n_embd), 行数由最大序列长度决定,而不是 vocab_size;查表用的索引是 0, 1, 2, ..., T-1 这几个位置编号,跟 token ID 无关。

两张表对照一览:

token_embedding_table position_embedding_table
行数(容量) vocab_size(词表大小,超参数固定) block_size(最大上下文长度,超参数固定)
查表用的索引 token ID(内容是什么) 位置编号 0..T-1(排第几)
行的含义 每个 token 的语义 每个位置的"顺序坐标"
表内数值 随机初始化,可学习 随机初始化,可学习(两张表都会被训练更新)
输出形状 (T, n_embd)(这里 T 是本次输入的 idx 长度) (T, n_embd)(广播对齐 tok_emb)

这一步承上启下:tok_emb 和 pos_emb 相加得到的 x,形状仍是 (B, T, n_embd), 这就是即将喂给 Head(或 MultiHeadAttention)去计算 q/k/v 的最终输入。

也就是说,进入 attention 之前,每个位置的向量已经同时携带了"内容"和"顺序"两种信息—— Head.forward 里 q = self.query(x) 这一步的 x,本身就是 tok_emb + pos_emb 的结果, 不是单纯的 token 语义向量。这也是为什么 attention 能够区分"同样的字在不同位置"的原因。

所以看到 B*T*C 或"T 个位置"这种表述时:

  • BTC:说的是张量形状,此时 T 强调的是"这批数据有多长"(sequence size 视角)
  • T 个位置的输出同时算出:说的是 attention 内部的计算行为,此时 T 强调的是"每个位置各自的身份和相互关系"(position 视角)

两种表述描述的是同一个维度 T,只是站在不同角度(数据组织 vs. 逐位置的语义/计算行为)去说而已,不是两个不同的东西。


Q2: Embedding 权重矩阵会保存并用于推理 — 是的,它就是普通参数

nn.Embedding.weight 和 nn.Linear.weight 没有任何区别: 都是 nn.Parameter,都参与梯度更新,都保存进 model.state_dict(),推理时直接加载复用。


Q3: Causal Attention 一次并行完成,不是 N 次循环 — Transformer vs RNN 的核心区别

RNN(旧方式): [10] → [10,20] → [10,20,30] → [10,20,30,40] → [10,20,30,40,50]
              需要 5 次串行前向传播,不能并行

Transformer(现在):
  输入 [10, 20, 30, 40, 50] 一次性全部喂入
  q @ k.T 一次计算出 (T, T) = (5, 5) 的全局相似度矩阵
  causal mask 把上三角置为 -inf
  softmax 后每个位置的 attention weight 自然满足"只看自己之前"的约束
  → 5 个位置的输出同时算出,完全并行

代价: 需要 O(T²) 的显存(存 T×T 的 attention 矩阵)
优势: 训练时一个 forward pass 同时优化 T 个预测目标

这就是 Transformer 取代 RNN 的根本原因:用空间换时间,把串行变并行。