8Transformer Block
x = x + self.sa(self.ln1(x)) # residual + Pre-Norm + attention
x = x + self.ffwd(self.ln2(x)) # residual + Pre-Norm + feedforward
Pre-Norm (normalize before the sublayer, not after) — more stable than the original Transformer paper. Residual (x + sublayer(x), not just sublayer(x)) guarantees ∂loss/∂x keeps a "+1" direct path, so gradients survive 4 stacked Blocks. Attention = tokens exchange info; FeedForward (64→256→64) = each position independently "thinks alone" — FFN holds ~2/3 of the model's parameters.
q@k.T). FFN and LayerNorm have zero — every (b,t) cell's output depends only on that cell's own input, full stop. Mechanically, FeedForward's matmul x @ W contracts the n_embd dimension (features), not T — unlike q@k.T, which contracts head_size specifically so T can interact with itself. Same shape of operation (a matmul), completely different purpose: one produces cross-position relationships, the other never touches them. Batching B and T together here is pure GPU efficiency — the same weights applied to many unrelated inputs at once — not a real data dependency the way attention's batching is.class FeedForward(nn.Module):
def __init__(self, n_embd):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.ReLU(),
nn.Linear(4 * n_embd, n_embd),
nn.Dropout(0.1),
)
def forward(self, x):
return self.net(x)
class Block(nn.Module):
def __init__(self, n_embd, n_head):
super().__init__()
head_size = n_embd // n_head
self.sa = MultiHeadAttention(n_head, head_size)
self.ffwd = FeedForward(n_embd)
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
def forward(self, x):
x = x + self.sa(self.ln1(x)) # residual + Pre-Norm + attention
x = x + self.ffwd(self.ln2(x)) # residual + Pre-Norm + feedforward
return x
nn.LayerNorm(n_embd) keeps two small learnable vectors, weight and bias, each shape (n_embd,); its forward normalizes each position's 64-dim vector to mean 0/var 1 then rescales by weight and shifts by bias — so "normalize" doesn't mean "no longer learnable". nn.Sequential in FeedForward just chains the 4 sub-modules' forward() calls in list order, nothing more.📓 Jupyter source — live from gpt-dev.ipynb, not hand-copied
cell 87af9589
# feedforward network # 怎么理解feedforward network呢?它是一个简单的两层全连接网络,输入是n_embd维的表示,输出也是n_embd维的表示,中间有一个非线性激活函数,这个网络的作用是对输入的表示进行进一步的变换和处理,捕捉输入数据中更复杂的模式或关系的信息 # feed的意思是前馈的,forward的意思是前向的,feedforward network就是一个前馈神经网络,表示信息在网络中是单向流动的,没有循环或反馈连接,这种网络结构使得它非常适合于处理固定大小的输入和输出,例如在自然语言处理任务中,输入是一段文本,输出是对文本的理解或生成结果 # 承接上面的多头输出的n_embd维的表示,feedforward network会对这个表示进行进一步的变换和处理,捕捉输入数据中更复杂的模式或关系的信息,这些信息对于模型的预测任务是有用的 class FeedForward(nn.Module): def __init__(self, n_embd): super().__init__() self.net = nn.Sequential( nn.Linear(n_embd, 4 * n_embd), # 将输入的n_embd维的表示映射到一个更高维的空间中,得到一个新的表示,这个表示包含了输入数据中更复杂的模式或关系的信息 nn.ReLU(), # 非线性激活函数,增加模型的表达能力,使得模型能够捕捉输入数据中更复杂的模式或关系的信息 nn.Linear(4 * n_embd, n_embd), # 将高维空间中的表示映射回n_embd维的空间中,得到一个新的表示,这个表示包含了输入数据中更复杂的模式或关系的信息 nn.Dropout(0.1), # dropout层,防止过拟合 ) def forward(self, x): return self.net(x)
cell 3f1a1809
# 前馈网络也属于前向传播的一部分,因此在多头self-attention层之后,我们会将多头自注意力层的输出传递给前馈网络,进行进一步的变换和处理,捕捉输入数据中更复杂的模式或关系的信息,这些信息对于模型的预测任务是有用的 # Block是Transformer模型中的一个基本组成部分,它包含了一个多头自注意力层和一个前馈网络,这两个组件都是前向传播的一部分,负责对输入数据进行变换和处理,捕捉输入数据中更复杂的模式或关系的信息,这些信息对于模型的预测任务是有用的 class Block(nn.Module): def __init__(self, n_embd, n_head): super().__init__() head_size = n_embd // n_head # sa 代表self-attention,ffwd代表feedforward network # 形状是 B,T,n_embd n_embd = n_head * head_size self.sa = MultiHeadAttention(n_head, head_size) # 形状是 B,T,n_embd,提升了模型的表达能力,使得模型能够捕捉输入数据中更复杂的模式或关系的信息 self.ffwd = FeedForward(n_embd) # 归一化层,规范化输入数据,稳定训练过程 # 归一化不影响形状,输入和输出的形状都是B,T,n_embd self.ln1 = nn.LayerNorm(n_embd) # layer normalization层,规范化输入数据,稳定训练过程 self.ln2 = nn.LayerNorm(n_embd) # layer normalization层,规范化输入数据,稳定训练过程 # x的形状是B,T,n_embd,输出的形状也是B,T,n_embd def forward(self, x): # 这里需要理解,因为Block已经是transformer的基本单位了,所以Block=>MultiHeadAttention+FeedForward+LayerNorm+残差连接,这些都是Transformer模型中的基本组件和机制 x = x + self.sa(self.ln1(x)) # 将多头自注意力层的输出与输入进行残差连接,得到一个新的表示,这个表示包含了输入数据中捕捉到的多个特定模式或关系的信息 x = x + self.ffwd(self.ln2(x)) # 将前馈网络的输出与输入进行残差连接,得到一个新的表示,这个表示包含了输入数据中捕捉到的更复杂的模式或关系的信息 return x
📝 笔记 Chinese notes — live from gpt-dev.ipynb, not hand-copied
note 508596c5
Block 解析:两行代码背后的三个设计决策
def forward(self, x): # x: (B, T, n_embd)
x = x + self.sa(self.ln1(x)) # 第一行
x = x + self.ffwd(self.ln2(x)) # 第二行
return x # 形状不变,仍是 (B, T, n_embd)
决策 1:残差连接(Residual Connection)— x = x + sublayer(x) 而不是 x = sublayer(x)
问题:深层网络(4个Block叠加 = 8次线性变换)梯度反向传播时会连乘缩小趋近于0,参数无法更新。
解法:加法 x + sublayer(x) 让梯度直接"跳过"子层流回去:
∂loss/∂x = ∂loss/∂output × (1 + ∂sublayer/∂x)
↑
这个 1 确保梯度不会消失
直觉:sublayer 只需要学习"需要改变什么"(delta),而不是"完整的新表示"。 如果什么都不需要改变,sublayer 的输出趋近于 0,x 直通到下一层。
决策 2:LayerNorm(在子层之前,Pre-Norm)— self.ln1(x)
将每个位置的 n_embd 维向量标准化到均值≈0、方差≈1。
为什么需要:n_layer 个 Block 叠加后,激活值的数值范围容易越来越大或越来越小。 LayerNorm 在每次进入子层前"归零",让每层都在相对稳定的数值范围内学习。
注意:这是 Pre-Norm(先 norm 再 sublayer),比原论文的 Post-Norm 训练更稳定。
决策 3:FeedForward 放在 Attention 之后 — 两种互补的操作
Self-Attention: 跨位置聚合信息 每个 token "问" 其他 token
信息在 T 个位置之间流动
FeedForward: 位置内独立变换 每个 token "自己思考"
n_embd → 4×n_embd → n_embd
位置之间完全独立,互不影响
类比:
- Attention = 一次讨论会(所有人交换信息)
- FFN = 各自回去独立写报告(消化吸收,提升表达能力)
4× 扩展的作用:给每个位置足够大的"工作空间"来做非线性变换,学习更复杂的模式。 FFN 的参数量占整个模型的约 2/3,它是真正"存储知识"的地方(attention 更多是"路由")。