GPTModel
→ TransformerBlock
→ TransformerLayer
一张 PyTorch 模型树是怎样被构建出来的?一次 forward 又怎样穿过它?沿这三个类,把配置、实例、张量和残差连接逐一对上。
本篇先使用常规逻辑形状:B 为 microbatch 大小,S 为序列长度,H 为 hidden size,Vₚ 为 padding 后的词表大小,T 为 TP size。需要时再加入 PP/VP 和词表 TP 分片;其他优化分支放到最后。
版本提示:这个快照的 GPTModel 已明确标为 deprecated,只接受关键 bug 修复,新增架构方向转向 HybridModel。当前 GPTModelBuilder 仍构造 GPTModel,因此它适合沿既有 GPT 主链学习;本篇不执行迁移。构造器 · 上游迁移说明
先确认:这三个类不是同一粒度
GPTModel 管语言模型的输入和输出;TransformerBlock 管当前分段的一组层;TransformerLayer 管一层里面的 Attention、MLP、Norm 和残差。这里的 Block 是“层栈”,不能与论文里有时称作 Transformer block 的“单层”混用。
Norm · Attention · BDA
Norm · MLP · BDA
独立模块实例
独立参数
不一定等于全模型层数
RoPE 对象也由模型建立,但它生成的位置参数会送入 Attention 的 Q/K 路径,不能画成“直接加到 token embedding 上”。可选 MTP 分支暂不展开。
| 对象 | 构建时负责 | forward 时负责 |
|---|---|---|
| GPTModel | embedding、位置参数生成器、decoder、输出投影、共享权重关系。 | 预处理 → 调 decoder → 后处理;选择返回 hidden、logits 或逐 token loss。 |
| TransformerBlock | 决定本地层列表、实例化各层、条件创建 final norm。 | 取得本段输入,安排执行上下文,遍历层,应用 final norm。 |
| TransformerLayer | 按 spec 组装 Norm、Attention、MLP、BDA 等子部件。 | Attention 子层与残差,再执行 MLP 子层与残差。 |
构建入口:配置 → spec → 模块实例
先把两条调用链分开。构建链创建 nn.Module、参数和子模块关系,通常在训练开始前执行;forward 链在每个 microbatch 上重复计算。ModuleSpec 参与前者,不是每次 forward 都重新解释和创建模型。
# 构建链:本版本默认 GPT 入口
GPTModelBuilder.build_model(...)
→ default_layer_spec(...) # 或采用传入的 spec
→ GPTModel(...)
→ TransformerBlock(...)
→ _get_block_submodules(...)
→ _build_layers(...)
→ TransformerLayer(...) × 本地层数
→ Norm / Attention / MLP / BDA
# forward 链:模块已经存在
GPTModel.forward(...)
→ _preprocess(...)
→ TransformerBlock.forward(...)
→ TransformerLayer.forward(...) × 本地层数
→ _postprocess(...)
2.1 Builder 决定构造条件
GPTModelBuilder.build_model 先解析 layer spec,再按配置 padding 词表,并根据 PP 和 VP 两者计算首尾标记。然后把 TransformerConfig、spec、Vₚ、位置信息、进程组和 stage 身份传给 GPTModel。
315# Determine pre/post flags if not provided using vp + pp stage316vp_size = self._model_config.virtual_pipeline_model_parallel_size317if pre_process is None:318 pre_process = is_vp_first_stage(vp_stage=vp_stage, vp_size=vp_size) and is_pp_first_stage(pg_collection.pp)319if post_process is None:320 post_process = is_vp_last_stage(vp_stage=vp_stage, vp_size=vp_size) and is_pp_last_stage(pg_collection.pp)pre_process=True 表示这个实例承担输入 embedding,post_process=True 表示承担模型输出侧。它们不是泛指“是否进行数据清洗”。无 PP/VP 时二者通常都为 True;有分段时由首尾位置决定。
build_distributed_models 则在更外层处理多个 chunks 及 mixed precision、DDP/FSDP 等包装。GPTModel 的构造器本身不会顺便建立完整训练循环、优化器或通信调度器。
2.2 ModuleSpec 是一份“组件选择说明”
它的核心字段是 module、params、submodules。例如,同一个 TransformerLayer 可以使用 local 的并行 Linear,也可以使用 TE 的融合 Norm+Linear;模型高层结构不必因此重写。
26module: Union[Tuple, type]27params: dict = field(default_factory=lambda: {})28submodules: object = None29metainfo: dict = field(default_factory=lambda: {})3031def __call__(self, *args: Any, **kwargs: Any) -> Any:32 """Builds an instance of the module from the spec.3334 Args:35 *args: Positional arguments to be passed to the module init.36 **kwargs: Keyword arguments to be passed to the module init.37 """38 return build_module(self, *args, **kwargs)build_module 解析模块类或导入路径,传入 spec 参数、调用处参数和子模块描述,最终实例化类。遇到 BDA 这样的函数,工厂会返回函数本身,留待执行时选择/调用。部分规范化层和 MLP 也通过 typed builder 直接构造,不能假定每个部件都经过同一个工厂。
TransformerConfig 描述尺寸与执行选项;ModuleSpec 描述组件实现组合;创建出的 nn.Module 才持有真正的参数,并参与 forward。GPTModel:把 token 世界接到 hidden-state 世界
3.1 构造器:按 stage 身份建立模型外壳
普通路径中,首 stage 建立 LanguageModelEmbedding,各 stage 建立本地 TransformerBlock,末 stage 建立词表输出层。RoPE/YaRN/M-RoPE 等配置决定位置参数对象;可选 MTP 另加预测模块。
265# Transformer.266self.decoder = TransformerBlock(267 config=self.config,268 spec=transformer_layer_spec,269 pre_process=self.pre_process,270 post_process=self.post_process,271 pg_collection=self.pg_collection,272 vp_stage=vp_stage,273 name="decoder" if self.config.quant_recipe is not None else None,274)这里没有逐层写 Attention 或 MLP。GPTModel 把 transformer_layer_spec、pg_collection 和 vp_stage 交给 Block,由后者进一步落实当前 stage 的模型结构。
pre_process=True · post_process=True
同一实例拥有输入、完整层栈和输出侧。假设 labels 已给定、TP=1,并开启常规 final norm,返回逐 token loss [B,S]。
无 MTP、无特殊 pipeline layout 的主线示意。真正的 PP 张量收发由调度器完成;这些类只消费当前 stage 所需输入。
3.2 Embedding:输入是 [B,S],主干通常是 [S,B,H]
LanguageModelEmbedding 先查 word embedding;仅使用 learned absolute position 时才把 position embedding 加上去。随后转换到模型主干的序列优先布局,并按配置处理 dropout、精度与 SP。
115word_embeddings = self.word_embeddings(input_ids)116if self.add_position_embedding:117 position_embeddings = self.position_embeddings(position_ids)118 embeddings = word_embeddings + position_embeddings119else:120 embeddings = word_embeddings121122if not self.reduce_scatter_embeddings:123 # Data format change to avoid explicit tranposes : [b s h] --> [s b h].124 embeddings = embeddings.transpose(0, 1).contiguous()RoPE 是另一条路径。GPTModel 在 _preprocess 生成 rotary 参数,沿 Block → Layer → Attention 传下去,作用在 Q/K 上。它与上面 learned absolute position 的加法不能画成同一个步骤。
LanguageModelEmbedding _preprocess
3.3 forward:预处理、主干、后处理
# 教学伪代码:省略可选分支与透传参数
def forward(input_ids, position_ids, attention_mask, labels=None, decoder_input=None):
decoder_input, rope, ... = self._preprocess(...)
hidden_states = self.decoder(
hidden_states=decoder_input,
attention_mask=attention_mask,
rotary_pos_emb=rope,
...
)
return self._postprocess(hidden_states, labels=labels, ...)
_preprocess 依次判断三个输入来源:有显式 decoder_input 就直接采用;否则首 stage 查 embedding;否则将局部变量置为 None,让 Block 从之前注入的 input_tensor 读取激活。
上述“直接采用”描述的是 _preprocess 这一层。显式 decoder_input 可绕过 embedding;但在 pre_process=False 的 PP stage,Block.forward 仍会以调度器注入的 self.input_tensor 覆盖传入 hidden_states,见下一节。
这不是把一个“空 tensor”送进 Attention。调度器收到上一个 stage 的激活后,会先调用 GPTModel.set_input_tensor,再转交给 decoder.set_input_tensor。P2P receive 属于调度层,不在 GPTModel.forward 里面。
670with backbone_context:671 hidden_states = self.decoder(672 hidden_states=decoder_input,673 attention_mask=attention_mask,674 inference_context=inference_context,675 rotary_pos_emb=rotary_pos_emb,676 rotary_pos_cos=rotary_pos_cos,677 rotary_pos_sin=rotary_pos_sin,678 rotary_pos_cos_sin=rotary_pos_cos_sin,679 packed_seq_params=packed_seq_params,680 sequence_len_offset=sequence_len_offset,681 padding_mask=padding_mask,682 **(extra_block_kwargs or {}),683 )上面是真实 decoder 调用:hidden states 是主要数值输入,mask、RoPE、packed sequence 元数据和 inference context 则解释这批张量该如何计算。普通 dense 训练只需抓住主链;其他参数先当作需要透传的执行上下文。
3.4 后处理:返回值由阶段和 labels 决定
| 条件 | 做什么 | 典型返回形状 |
|---|---|---|
| post_process=False | 直接交出本段 hidden states,供下一个 stage 使用。 | [S,B,H] |
| 末段,labels=None | LM head 产生 logits,最后交换 batch/sequence 两个轴。 | [B,S,Vₚ/T];gather 后为 [B,S,Vₚ] |
| 末段,给定 labels | 通过 vocab-parallel cross entropy 得到逐 token loss。 | [B,S],不是一个标量 |
899if labels is None:900 # [s b h] => [b s h]901 return logits.transpose(0, 1).contiguous()902903loss = self.compute_language_model_loss(labels, logits)904905return loss源码这里的转置注释使用了 h,但此时 tensor 已经是 logits,最后一维应该理解为词表轴,而不是 hidden size。默认 parallel_output=True 保留词表 TP 分片,交叉熵实现知道该布局,不要求先 gather 全词表。
125# [b s] => [s b]126labels = labels.transpose(0, 1).contiguous()127loss = self.vocab_parallel_cross_entropy(logits, labels, self.tp_group)128# [s b] => [b, s]129return loss.transpose(0, 1).contiguous()模型得到的 [B,S] loss 还要交给上层 loss_func:应用 loss mask,统计有效 token,再与调度器/梯度收尾共同完成训练归一化。不要在 GPTModel 内寻找完整的 scalar loss、backward 或 optimizer.step。
3.5 Tied weights:共享语义与共享内存是两件事
开启 share_embeddings_and_output_weights 后,输入 embedding 和 LM head 使用同一套词表权重。单 stage 时可以让 output layer 不分配自己的权重,在调用时显式传入 embedding weight。
跨 PP 时,首尾位于不同 rank,不能共享同一个 Python Parameter;它们维护同值副本,通过 embedding group 的初始化同步和后续梯度同步保持一致。模型构造/forward 与训练梯度收尾共同实现这项语义。
TransformerBlock:构建本地层栈,组织逐层执行
4.1 先把 spec 整理成一张本地层列表
_get_block_submodules 接受两类常见输入:已经明确列好的 TransformerBlockSubmodules,或者描述单层的 ModuleSpec。后者要先计算当前 stage 的层数,再重复该 spec 形成列表。
257elif issubclass(spec.module, BaseTransformerLayer):258 num_layers = get_num_layers_to_build(config, vp_stage, pp_rank)259 return TransformerBlockSubmodules(260 layer_specs=[spec] * num_layers, layer_norm=LayerNormImpl261 )[spec] * num_layers 重复的是“构造说明”,不是已经建立的模型参数。随后 _build_layers 每次都创建新实例,并放进 PyTorch ModuleList,从而被注册到模型参数树。
399# offset is implicit in TransformerLayer400self.layers = torch.nn.ModuleList(401 [402 build_layer(layer_spec, i + 1)403 for i, layer_spec in enumerate(self.submodules.layer_specs)404 ]405)如果输入已经是按层列好的 Block spec,get_gpt_decoder_block_spec 等上层代码会先按 PP/VP 或指定 layout 切出本段 specs,Block 不应再把它当成全模型列表重复切分。
4.2 层数、局部下标与全局层号
get_num_layers_to_build 决定“建多少层”;get_transformer_layer_offset 决定“从全局哪里开始”。局部 layers[i] 是 0-based 容器下标,传给构造器的层号从 1 开始;TransformerLayer 再加上本 stage 的 offset 得到全局 layer_number。
每个 Block 只有 2 层;一个物理 stage 持有两个 chunks,共 4 层。忽略 embedding/loss 独立分配与自定义 layout;不能把这个均分例子当作全部配置的公式。
offset = vp_stage × (N / VP) + pp_rank × 每 chunk 层数
global_layer_number = local_layer_number + offset
全局层号用于层特定配置、量化上下文、推理 cache 等;它与容器下标的区别会在 PP/VP 下变得重要。变量 num_layers_per_pipeline_rank 在这个 Block 中来自 len(self.layers),有 VP 时应读作当前 chunk 的层数。
4.3 forward:输入槽 → 执行上下文 → 遍历层 → final norm
# 教学伪代码:普通 eager 主线,省略扩展参数
def forward(hidden_states, ...):
if not self.pre_process:
hidden_states = self.input_tensor
hidden_states = make_viewless_tensor(hidden_states, keep_graph=True)
with rng_context, quantization_context:
if self.training and recompute_granularity == "full":
hidden_states = checkpointed_forward(...)
else:
for layer in self.layers:
with offload_context, per_layer_quantization_context:
hidden_states, context = layer(hidden_states, ...)
if self.final_layernorm is not None:
hidden_states = self.final_layernorm(hidden_states)
return hidden_states
这里的 make_viewless_tensor(..., keep_graph=True) 是为了满足流水线释放输出存储等机制对 tensor view 的约束,不是 detach,也不是停止反向传播。SP 的 RNG context、FP8/FP4 的 recipe context、offload 和 recompute 控制状态生命周期;它们包围逐层计算,但没有改变这三个类的职责划分。
普通路径每次调用 layer 得到 (hidden_states, context)。decoder-only GPT 的 cross-attention context 通常不用;Block 仍保留通用接口。默认 Block 最后只返回 hidden tensor;请求中间层特征时则有额外返回分支。
完整 Block.forward set_input_tensor full recompute
4.4 Final norm 由谁决定
普通无 MTP 时,只有 layer_norm 存在且 post_process、post_layer_norm 都为真,才在该 Block 上创建 final norm。带 MTP 时则放在包含最后一个 decoder layer 的 stage,不再简单跟随模型输出端。
post_layer_norm 是“层栈之后是否有 final norm”的开关。它不能被解释成每个 TransformerLayer 使用 post-norm 架构。每层内部的 Norm/残差顺序要看 Layer 和选中的 spec。
TransformerLayer:两条子层分支,两次残差相加
5.1 构造器把逻辑部件变成具体实现
Layer 保存全局层号与进程组,构建 input norm、self-attention、self-attention BDA、cross-attention 三件套、pre-MLP norm、MLP 和 MLP BDA,再设置 selective recompute 等选项。普通 GPT 的 cross-attention 部件保持默认 Identity,因此不会执行真实 encoder–decoder attention。
| 逻辑角色 | 成员 | 实现位置 |
|---|---|---|
| Attention 前归一化 | input_layernorm | 显式 Norm,或融合进 QKV projection。 |
| Attention 分支 | self_attention | QKV → 位置/相关变换 → core attention → output projection。 |
| 第一处残差合并 | self_attn_bda | 最后投影 bias + dropout + residual add。 |
| MLP 前归一化 | pre_mlp_layernorm | 显式 Norm,或融合进 FC1。 |
| MLP 分支 | mlp | FC1 → activation/gating → FC2;也可替换成 MoE。 |
| 第二处残差合并 | mlp_bda | 使用 Attention 合并后的 x₁ 作为新的 residual。 |
5.2 forward 的骨架其实很短
# 对实际 forward 主体的提炼;省略观测、kwargs 与扩展处理
hidden_states, context = self._forward_attention(*args, **kwargs)
output = self._forward_mlp(hidden_states, inference_context, ...)
return output, context
_forward_attention 经 helper 完成第一条分支和残差,再走普通 GPT 的 Identity cross-attention;_forward_mlp 完成第二条分支。把这两个 helper 打开后,数学上就是:
x₂ = x₁ + Dropout(MLP(Norm₂(x₁)) + bias_mlp)
这里 Attention / MLP 输出指尚未加最后输出投影 bias 的分支结果;bias 可以是 None。公式限定普通标准残差主线,不覆盖融合推理、mHC 等改写路径。
① 保存 x₀,然后归一化分支输入
第一条残差保留进入这一层的原始 hidden states。Norm 的输出送给 Attention;最终相加使用原始 x₀。
六步用于展示逻辑顺序,不表示六个独立 kernel。TE 模式里 ①+② 的 QKV 部分、④+⑤ 的 FC1 部分发生融合;推理融合路径还可能合并 BDA。
Layer.forward Attention 分支 MLP 分支 第一条 residual 第二条 residual
5.3 BDA 为什么独立出来
BDA 是 bias–dropout–add。Attention 和 MLP 的末端投影可以返回 (output, bias),让 bias addition、dropout 和 residual addition 集中执行,从而选择 fused/unfused 实现。这不表示所有 Linear 的 bias 都被推迟:例如 FC1 的 bias 仍需要在激活前处理。
42if bias is not None:43 if inplace:44 x.add_(bias)45 else:46 x = x + bias47 out = torch.nn.functional.dropout(x, p=prob, training=training, inplace=inplace)48 if inplace:49 out.add_(residual)50 else:51 out = residual + out52 return out53else:54 out = torch.nn.functional.dropout(x, p=prob, training=training, inplace=inplace)55 if inplace:56 out.add_(residual)57 else:58 out = residual + out59 return out注意 residual + out 所在位置:残差由 TransformerLayer 的 BDA 合并,MLP 子模块只计算分支结果,不自行实现整层的第二条残差。融合选择由 get_bias_dropout_add(training, fused) 完成。
BDA 实现选择 Attention BDA MLP BDA
5.4 Local 与 TE:Identity 不等于没有 Norm
阅读 TE spec 时,会看到独立的 input_layernorm 和 dense 的 pre_mlp_layernorm 保持 Identity。原因是归一化被放进融合的 Linear 模块里;逻辑上的 pre-norm 顺序仍然存在。
| 逻辑计算 | 普通 local spec | 普通 dense TE spec |
|---|---|---|
| Norm₁ + QKV | 独立 Norm → ColumnParallelLinear | 独立 Norm 为 Identity;TELayerNormColumnParallelLinear 包含 Norm 和投影。 |
| Core attention | DotProductAttention | TEDotProductAttention |
| Attention 输出投影 | RowParallelLinear | TERowParallelLinear |
| Norm₂ + FC1 | 独立 Norm → ColumnParallelLinear | dense 的独立 Norm 为 Identity;Norm 融合进 FC1。 |
| FC2 | RowParallelLinear | TERowParallelLinear |
这张表限定普通 dense、非 MLA 路径。MoE 的路由/专家组织不同,TE 下 pre-MLP norm 可以重新成为显式模块;其他 layer spec 也可能改变组合。必须把 Layer.forward 和选中的 spec 放在一起读。
TE spec 入口 local spec 入口 TE backend 提供者 local backend
5.5 Attention 与 MLP 先读到接口边界
Attention:QKV projection → 位置编码/QK 处理 → core attention → output projection → (output, bias)。不同实现可以融合中间计算,不能假设一定物化完整的 [B,heads,S,S] attention 矩阵;TP 具体通信和 attention kernel 留待下一课。
MLP:FC1 → bias 与 activation/gating → FC2 → (output, output_bias)。如果采用 GLU 类门控,会拆分 FC1 的输出,计算 activation(gate) × value。中间宽度由 ffn_hidden_size 和 gating 配置决定,不应一律写成 4H。
把三层调用串起来
现在取一个简单例子:B=2、S=8、H=16、Vₚ=64,TP=PP=1,两个 dense 层,使用 RoPE,labels 已给定,无特殊分支。数字只用于追踪形状,不是建议的训练配置。
| 调用位置 | 传入 / 当前值 | 产物 |
|---|---|---|
| GPTModel._preprocess | input_ids、position_ids [2,8] | embedding [8,2,16];另生成 RoPE 参数。 |
| TransformerBlock.forward | hidden [8,2,16] | 进入本地两个 Layer 的循环。 |
| Layer 1 / Attention | x₀;保留第一条 residual | Norm → Attention → BDA,得到 x₁ [8,2,16]。 |
| Layer 1 / MLP | x₁;保留第二条 residual | Norm → MLP → BDA,得到 x₂ [8,2,16]。 |
| Layer 2 → Block final norm | 上一层输出 | decoder 最终 hidden [8,2,16]。 |
| GPTModel._postprocess | hidden → LM head | logits [8,2,64]。 |
| compute_language_model_loss | labels 转为 [8,2],与 logits 做 CE | 返回逐 token loss [2,8]。 |
| 上层训练回调 | token loss 与 loss_mask | 用于反传的损失统计与 token 数,再按训练配置归一化。 |
如果只把 labels 改为 None,末端返回 [2,8,64] logits;如果开启 TP=2 且保留词表分片,输出 logits 的本地词表轴是 32;如果当前实例是中间 PP stage,连 LM head 都不会运行,返回的是本段 hidden states。
读完这一层,应该能回答四个问题
当前实例有哪些子模块?forward 输入来自 tokens 还是上个 stage?哪一个对象保存并相加 residual?本次返回的是 hidden、logits,还是 token loss?
先安放扩展分支,再选择下一条深入路径
| 扩展 | 改变哪一部分 | 本篇保留的边界 |
|---|---|---|
| Full / selective recompute | Block 对层/层组重计算;Layer 对 norm/MLP 等局部选择保存与重算。 | 改变激活生命周期,不是把 loss 或参数更新移进模型。 |
| FP8 / FP4 / offload | 初始化与 forward 的 context、参数/激活存储与执行后端。 | 不能概括为全模型统一 cast;不同 recipe 与硬件有约束。 |
| Inference / KV cache / CUDA Graph | Attention cache、position offset、最后 token logits、图重放与融合路径。 | InferenceMode.is_active() 是专门状态,不能与单独调用 model.eval() 等同。 |
| MoE / MTP | MoE 替换 MLP;MTP 增加预测与 loss 路径,并影响 stage / final norm 归属。 | 不是简单往当前伪代码末尾加一行。 |
| mHC / wide residual / Hybrid | 残差组织或层类型组合发生变化。 | 本篇标准残差两条公式不能自动推广到这些模式。 |
| SP / CP / packing | 当前 rank 持有的序列布局与元数据发生变化。 | [S,B,H] 先作为普通逻辑视图,局部 tensor shape 需另查。 |
下一步最自然的两个方向是:沿 SelfAttention → QKV → core attention → output projection 理解 attention 的计算与 TP 通信;或者先沿 ModuleSpec → TE/local Linear 理解同一数学层如何落到不同后端。此时再研究 DP 梯度 buffer、PP 调度,会更容易分清模型计算与执行组织的边界。
逐项源码阅读清单
先固定一个具体配置再读调用链。看到分支时记录“触发条件、替换的模块、改变的 tensor 布局”,不要把互斥路径拼成一条不存在的执行流程。