9Stack ×n_layer
4 identical Blocks, same shape all the way through — "layer" and "Block" are the same thing, n_layer counts these arrows
self.blocks = nn.Sequential(*[Block(n_embd, n_head) for _ in range(n_layer)])
x = self.blocks(x)
(B,T,64) → 4× Block → (B,T,64)
n_layer=4 Blocks stacked, shape never changes — only the content gets progressively refined, each Block adding another round of attention (relate to other positions) + FFN (digest alone).
"layer" and "Block" are literally the same thing here —
n_layer is exactly the count of Block instances created by range(n_layer) below, and this is standard GPT-family terminology, not a notebook-specific quirk (HuggingFace's own GPT-2 config defines n_layer the same way). Two things worth being precise about: (1) the 4 Blocks are not the same Block reused 4 times — each has its own independently-initialized, independently-trained Wq/Wk/Wv/FFN weights; (2) every Block's input/output shape is identically (B,T,64), which is why nn.Sequential can chain them with zero adapter code — one Block's full output becomes the next Block's full input, unchanged.Fixed since this page was first written:
x = self.blocks(x) is active in the current notebook. It was accidentally commented out for a while — the model ran with attention/FFN completely bypassed — but that's since been corrected. A fresh run now shows loss ≈4.4090 with the 4 real Blocks actually contributing. Worth knowing the bug existed at all: nn.Sequential(*[...]) still registers all 4 Block submodules (visible in print(model), included in .parameters()) even while the line calling them was commented out — a module being defined and a module actually running are separate things PyTorch won't warn you about.full source — BigramLanguageModel (gpt-dev.ipynb)the once-bypassed line, now confirmed active
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) <-- active: was accidentally commented out earlier, now fixed
x = self.ln_f(x) # (B,T,C)
logits = self.lm_head(x) # (B,T,vocab_size)
PyTorch internals (why this bug was easy to miss):
nn.Sequential(*[...]) unpacks a Python list of 4 Block instances as positional arguments — each still gets registered as a proper submodule (visible in print(model), its parameters included in .parameters()) whether or not forward() ever calls it. That's exactly why the earlier commented-out call line was so easy to miss — print(model) looked completely correct either way; only autograd tracing (and the fact those weights never budged during training) would have revealed the Blocks weren't actually running.📓 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