Merged
[refactor](dsv4): Reuse dsv4 MTP module form upstream #1199
zhangjiansheAdd on 29 days ago
[refactor](dsv4): Reuse dsv4 MTP module form upstream #1199
Merged
Total: 12 files changed+527-629
| @@ -52,18 +52,22 @@ MTP block 复用 DeepSeek-V3.2 的 DSA attention 配置,但拥有独立参数 | |||
| 52 | 52 | ||
| 53 | ### 1.3 DeepSeek-V4 MTP | 53 | ### 1.3 DeepSeek-V4 MTP |
| 54 | 54 | ||
| 55 | -DeepSeek-V4 主干使用 mHC,多流 hidden state 的形状为 `[batch, sequence, hc_mult, hidden]`。MTP 过程中不能先把这些 stream 合并成普通三维 hidden,否则会丢失 mHC 状态。每个 DeepSeek-V4 MTP block 执行: | 55 | +DeepSeek-V4 主干使用 mHC,多流 hidden state 的形状为 `[tokens, hc_mult, hidden]`。MTP 过程中不能先把这些 stream 合并成普通二维 hidden,否则会丢失 mHC 状态。每个 DeepSeek-V4 MTP block 执行: |
| 56 | 56 | ||
| 57 | 1. 分别投影未来 token embedding 和上一深度的多流 hidden state; | 57 | 1. 分别投影未来 token embedding 和上一深度的多流 hidden state; |
| 58 | 2. 将 token embedding 投影广播到每个 mHC stream; | 58 | 2. 将 token embedding 投影广播到每个 mHC stream; |
| 59 | 3. 通过 `HcPre -> Attention -> HcPost` 更新 attention 分支; | 59 | 3. 通过 `HcPre -> Attention -> HcPost` 更新 attention 分支; |
| 60 | 4. 通过 `HcPre -> FFN/MoE -> HcPost` 更新 FFN 分支; | 60 | 4. 通过 `HcPre -> FFN/MoE -> HcPost` 更新 FFN 分支; |
| 61 | -5. 使用当前深度独立的 `HcHead` 生成三维 prediction hidden; | 61 | +5. 使用当前深度独立的 `HcHead` 生成二维 prediction hidden; |
| 62 | -6. 三维 prediction hidden 进入共享 LM head,多流 hidden state 则继续传给下一 | 62 | +6. 二维 prediction hidden 进入共享 LM head,多流 hidden state 则继续传给下一 |
| 63 | 个 MTP 深度。 | 63 | 个 MTP 深度。 |
| 64 | 64 | ||
| 65 | DeepSeek-V4 MTP 保留 mHC 多流状态,但其 attention 使用非压缩形式,不启用主干 DSA 的 compressor 和 indexer。 | 65 | DeepSeek-V4 MTP 保留 mHC 多流状态,但其 attention 使用非压缩形式,不启用主干 DSA 的 compressor 和 indexer。 |
| 66 | 66 | ||
| 67 | +NPU 主干 block 保留原有适配;MTP block 直接使用上游 `MTPBlock`,复用其 mask、融合投影、mHC 更新及预测归一化。配置仍构建当前 NPU attention、MoE 和 mHC 组件;decoder 在调用 block 时选择对应的 metadata 并传入 positions。`DeepSeekV4Model` 直接继承 `Decoder`,在 `model.py` 中持有 `mtp_layers` 并通过 `mtp_forward` 执行辅助深度;MTP batch 构造、chunked loss 与梯度隔离辅助逻辑位于 V4 的 `mtp.py`。 | ||
| 68 | + | ||
| 69 | +当前固定上游提交 `ebdfc8c` 已包含 V3 的多输出 chunked loss 支持。V4 沿用本仓的 MTP loss 封装,以接入 CP 预切分 labels 和共享 LM head 的梯度隔离。 | ||
| 70 | + | ||
| 67 | ### 1.4 DeepSeek-V4 Context Parallel | 71 | ### 1.4 DeepSeek-V4 Context Parallel |
| 68 | 72 | ||
| 69 | MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移动会在 rank 边界读到不属于本 rank 的 token。V4 的 CP 布局由切分施加(`--parallelism.context-parallel-load-balancer doc_chunk`,见[Context Parallel](context_parallel.md)),实现因此保持在 `cp_shard` 之前对完整序列统一生成: | 73 | MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移动会在 rank 边界读到不属于本 rank 的 token。V4 的 CP 布局由切分施加(`--parallelism.context-parallel-load-balancer doc_chunk`,见[Context Parallel](context_parallel.md)),实现因此保持在 `cp_shard` 之前对完整序列统一生成: |
| @@ -72,17 +76,15 @@ MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移 | |||
| 72 | - packed sequence 感知的有效位置 mask; | 76 | - packed sequence 感知的有效位置 mask; |
| 73 | - 每个 MTP 深度的监督 label。 | 77 | - 每个 MTP 深度的监督 label。 |
| 74 | 78 | ||
| 75 | -这些张量在 `preprocess_inputs` 中先于基座切分、在全局行上构建;随后 `super().preprocess_inputs()` 完成 `inputs`/`labels`/`positions` 的切分,MTP 三个张量再用**同一把连续切片**单独 `cp_shard`(本地切片,无通信),保证 token、label 和 mask 与 `inputs` 在每个 rank 上严格同位。 | 79 | +`model.py` 的 `DeepSeekV4Model.preprocess_inputs` 在 MTP 启用时先准备全局 MTP batch,并应用输入的 padding mask。主输入、labels 和 positions 走原有 decoder 预处理,MTP batch 随后用相同的 `doc_chunk` 布局和全局 positions 单独切分。前向按深度取本地 token 和 mask,chunked loss 读取对应的本地辅助 labels。关闭 CP 时,模型直接使用准备好的全局 MTP batch。 |
| 76 | 80 | ||
| 77 | -该流程只接入 DeepSeek-V4:继续复用已有压缩 metadata 和 CP plan 构造;MTP 张量的切分是独立的一次 `cp_shard` 调用,与 `inputs`/`labels`/`positions` 的切分使用同一把连续切片。DeepSeek-V3 和 DeepSeek-V3.2 保留社区 MTP 的原有限制,`context_parallel_degree > 1` 时在配置更新阶段报错;DeepSeek-V3.2 的 varlen attention 本身也不支持 CP,DeepSeek-V3 已有的非 MTP CP 路径不变。 | 81 | +该流程只接入 DeepSeek-V4,继续复用已有 metadata 和 CP plan。DeepSeek-V3.2 保留社区 MTP 的 CP 限制。本仓 CP 实现仍要求 fused attention;CPU 输入处理检查不能替代真实 NPU CP 训练验证。 |
| 78 | - | ||
| 79 | -该处理与 Megatron-LM MTP 在 CP 边界交换 future token/label 的数学目标一致;区别是 TorchTitan 的模型 metadata hook 位于 CP 切分之前,因此可直接在全局序列上生成,再按和输入相同的连续切法单独切分,无需额外点对点通信。 | ||
| 80 | 82 | ||
| 81 | ### 1.5 Chunked loss | 83 | ### 1.5 Chunked loss |
| 82 | 84 | ||
| 83 | -DeepSeek-V4 的默认 recipe 使用 `MTPChunkedLossWrapper`。它继承并逐预测分支调用 TorchTitan 原生 `ChunkedLossWrapper`,因此复用其 sequence chunk、LM head FSDP、梯度累加和 decoder backward bridge。主分支权重为 `1`,每个 MTP 分支权重为 `mtp_scale / K`。 | 85 | +DeepSeek-V4 在启用 MTP 的 recipe 中使用 `MTPChunkedLossWrapper`。它继承并逐预测分支调用 TorchTitan 原生 `ChunkedLossWrapper`,因此复用其 sequence chunk、LM head FSDP、梯度累加和 decoder backward bridge。主分支权重为 `1`,每个 MTP 分支权重为 `mtp_scale / K`。 |
| 84 | 86 | ||
| 85 | -分支权重在分块 loss 内部、内部 `backward()` 之前应用,而不是在最终标量上事后相乘。这样 LM head 和 decoder hidden gradient 都与未分块 MTP loss 保持相同缩放,同时避免构造完整 `[batch, sequence, vocab]` logits。 | 87 | +分支权重在分块 loss 内部、内部 `backward()` 之前应用,而不是在最终标量上事后相乘。这样 LM head 和 decoder hidden gradient 都与未分块 MTP loss 保持相同缩放,同时避免构造完整 `[tokens, vocab]` logits。 |
| 86 | 88 | ||
| 87 | DeepSeek-V3.2 不适配 chunk loss,直接复用社区 `list[logits] + MTPLoss` 训练路径。 | 89 | DeepSeek-V3.2 不适配 chunk loss,直接复用社区 `list[logits] + MTPLoss` 训练路径。 |
| 88 | 90 | ||
| @@ -113,11 +115,11 @@ TorchTitan-NPU 只补充社区当前尚未提供的组合能力: | |||
| 113 | 115 | ||
| 114 | | 对象 | 职责 | | 116 | | 对象 | 职责 | |
| 115 | |---|---| | 117 | |---|---| |
| 116 | -| `prepare_mtp_batch` | 为 DeepSeek-V4 在 CP 之前生成各深度 token、mask 和 label | | 118 | +| `prepare_mtp_batch` | 在 CP 切分前准备各深度 token、mask 和 label | |
| 117 | | `MTPChunkedLossWrapper` | 为 DeepSeek-V4 将原生 chunked loss 扩展到主预测和各 MTP 预测 | | 119 | | `MTPChunkedLossWrapper` | 为 DeepSeek-V4 将原生 chunked loss 扩展到主预测和各 MTP 预测 | |
| 118 | | `SharedLinear` | MTP 投影期间使用 detached 权重,保留输入梯度及原模块的 FSDP 调用路径 | | 120 | | `SharedLinear` | MTP 投影期间使用 detached 权重,保留输入梯度及原模块的 FSDP 调用路径 | |
| 119 | 121 | ||
| 120 | -DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造和并行入口。DeepSeek-V4 复用 `roll_mtp_sequence` 和社区多预测列表接口,只实现 mHC 多流状态、CP 和 chunk loss 所需的专用 decoder 与 block。只有 DeepSeek-V4 的专用 decoder 配置放开 MTP 与 CP 的组合;没有修改社区 `MTPDecoder` 或 `MTPLoss`。 | 122 | +DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造和并行入口。DeepSeek-V4 直接使用社区 `MTPBlock` 和 `roll_mtp_sequence`,由 `DeepSeekV4Model(Decoder)` 统一管理主干和 MTP,不再定义独立 MTP decoder 或 block 子类。本仓补充 CP、chunked loss 和梯度隔离所需的输入与梯度处理;没有修改社区 `MTPDecoder` 或 `MTPLoss`。 |
| 121 | 123 | ||
| 122 | ### 2.2 DeepSeek-V3.2 目录 | 124 | ### 2.2 DeepSeek-V3.2 目录 |
| 123 | 125 | ||
| @@ -134,9 +136,9 @@ DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造 | |||
| 134 | | 文件 | MTP 相关职责 | | 136 | | 文件 | MTP 相关职责 | |
| 135 | |---|---| | 137 | |---|---| |
| 136 | | `deepseek_v4/__init__.py` | 根据模型规格构造非压缩、mHC-aware 的 MTP blocks | | 138 | | `deepseek_v4/__init__.py` | 根据模型规格构造非压缩、mHC-aware 的 MTP blocks | |
| 137 | -| `deepseek_v4/model.py` | 保留主干多流 state,并组织主预测和 MTP 预测 | | 139 | +| `deepseek_v4/model.py` | 保留原主干适配,管理 MTP 前向与 CP 预处理 | |
| 138 | -| `deepseek_v4/mtp.py` | 实现 DeepSeek-V4 mHC MTP block、CP batch 和 chunk loss | | 140 | +| `deepseek_v4/mtp.py` | 构造全局 MTP batch,适配多分支 chunked loss 与梯度隔离 | |
| 139 | -| `deepseek_v4/config_registry.py` | 默认 recipe 构造 MTP 模型并配置 MTP chunk loss | | 141 | +| `deepseek_v4/config_registry.py` | 根据 `num_mtp_layers` 配置模型和对应的 chunked loss | |
| 140 | | `deepseek_v4/parallelize.py` | 让 MTP blocks 复用现有 DSV4 并行流程 | | 142 | | `deepseek_v4/parallelize.py` | 让 MTP blocks 复用现有 DSV4 并行流程 | |
| 141 | | `deepseek_v4/sharding.py` | 增加 MTP fusion、mHC head 和有效掩码布局 | | 143 | | `deepseek_v4/sharding.py` | 增加 MTP fusion、mHC head 和有效掩码布局 | |
| 142 | | `deepseek_v4/state_dict_adapter.py` | 转换本地 `mtp_layers` 与 HF `mtp.<depth>` 参数 | | 144 | | `deepseek_v4/state_dict_adapter.py` | 转换本地 `mtp_layers` 与 HF `mtp.<depth>` 参数 | |
| @@ -159,16 +161,20 @@ Pipeline Parallel(PP),启用时必须保持 `context_parallel_degree=1` | |||
| 159 | 161 | ||
| 160 | ## 3. 使能方式 | 162 | ## 3. 使能方式 |
| 161 | 163 | ||
| 162 | -### 3.1 默认 recipe | 164 | +### 3.1 启用 DeepSeek-V4 MTP |
| 163 | 165 | ||
| 164 | -DeepSeek-V4 的默认 recipe 已经启用 MTP,不需要额外提供只转调默认配置的 `deepseek_v4_debugmodel_mtp` | 166 | +DeepSeek-V4 普通 recipe 的 `num_mtp_layers` 默认是 `0`。在自定义 recipe 中显式启用一层 MTP: |
| 165 | 167 | ||
| 166 | -```text | 168 | +```python |
| 167 | -DeepSeek-V4: | 169 | +from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel |
| 168 | - --module torchtitan_npu.models.deepseek_v4 | 170 | + |
| 169 | - --config deepseek_v4_debugmodel | 171 | + |
| 172 | +def deepseek_v4_mtp(): | ||
| 173 | + return deepseek_v4_debugmodel(num_mtp_layers=1) | ||
| 170 | ``` | 174 | ``` |
| 171 | 175 | ||
| 176 | +已有集成测试 `tests.integration_tests.mtp_config.deepseek_v4_debugmodel_mtp` 使用相同入口。GraphTrainer recipes 仍关闭 MTP。 | ||
| 177 | + | ||
| 172 | 该 recipe 会构造一个 MTP 深度,并使用 `MTPChunkedLossWrapper.Config`;其内部仍使用标准 `CrossEntropyLoss`。DeepSeek-V3.2 不在 NPU `config_registry.py` 中重复声明 MTP recipe,模型侧直接复用社区 MTP 能力。 | 178 | 该 recipe 会构造一个 MTP 深度,并使用 `MTPChunkedLossWrapper.Config`;其内部仍使用标准 `CrossEntropyLoss`。DeepSeek-V3.2 不在 NPU `config_registry.py` 中重复声明 MTP recipe,模型侧直接复用社区 MTP 能力。 |
| 173 | 179 | ||
| 174 | 模型和 loss 必须同时切换。只构造 MTP layers 而继续使用普通 loss,或者只配置 `MTPLoss` 而没有构造 MTP layers,都会造成模型输出与 loss 输入不匹配。 | 180 | 模型和 loss 必须同时切换。只构造 MTP layers 而继续使用普通 loss,或者只配置 `MTPLoss` 而没有构造 MTP layers,都会造成模型输出与 loss 输入不匹配。 |
| @@ -209,8 +215,8 @@ config.loss = MTPChunkedLossWrapper.Config( | |||
| 209 | | `num_chunks` | DeepSeek-V4 每个主/MTP hidden sequence 的 loss 分块数 | | 215 | | `num_chunks` | DeepSeek-V4 每个主/MTP hidden sequence 的 loss 分块数 | |
| 210 | | `mtp_layers` | 模型内部展开后的 MTP block 配置列表,通常不手工构造 | | 216 | | `mtp_layers` | 模型内部展开后的 MTP block 配置列表,通常不手工构造 | |
| 211 | 217 | ||
| 212 | -DeepSeek-V4 默认 recipe 使用 `mtp_scale=0.3`。 | 218 | +DeepSeek-V4 MTP chunked loss 默认使用 `mtp_scale=0.3`。 |
| 213 | 219 | ||
| 214 | ### 3.3 关闭 MTP | 220 | ### 3.3 关闭 MTP |
| 215 | 221 | ||
| 216 | -关闭 MTP 时需要让模型构造保持 `num_mtp_layers=0`,并使用普通 loss。此时 `config.mtp_layers` 为空列表,运行时 `model.mtp_layers is None`;模型不创建 MTP 参数,训练只计算主 MTP loss。 | 222 | +DeepSeek-V4 使用 `num_mtp_layers=0` 并配合普通 loss 关闭 MTP。此时 `config.mtp_layers` 为空列表,运行时 `model.mtp_layers` 为空的 TorchTitan `ModuleList`,不创建 MTP 参数,训练只计算主预测 loss。V3.2 的关闭参数仍为 `num_mtp_layers=0`。 |
| @@ -51,6 +51,7 @@ def _build_case( | |||
| 51 | extra_override_imports: tuple[str, ...] = (), | 51 | extra_override_imports: tuple[str, ...] = (), |
| 52 | env_vars: dict[str, str] | None = None, | 52 | env_vars: dict[str, str] | None = None, |
| 53 | disabled: bool = False, | 53 | disabled: bool = False, |
| 54 | + use_cp_attention: bool = False, | ||
| 54 | ) -> OverrideDefinitions: | 55 | ) -> OverrideDefinitions: |
| 55 | """Build one DeepSeek-V4 integration case. | 56 | """Build one DeepSeek-V4 integration case. |
| 56 | 57 | ||
| @@ -60,6 +61,11 @@ def _build_case( | |||
| 60 | checking. | 61 | checking. |
| 61 | """ | 62 | """ |
| 62 | recipe = GOLDEN_OVERRIDES if use_golden else NPU_OVERRIDES | 63 | recipe = GOLDEN_OVERRIDES if use_golden else NPU_OVERRIDES |
| 64 | + if use_cp_attention: | ||
| 65 | + # The CP recipe selects the fused CP backend before Trainer config validation. | ||
| 66 | + recipe = tuple( | ||
| 67 | + arg for arg in recipe if not arg.startswith("torchtitan_npu.override.deepseek_v4.sparse_attn.asc=") | ||
| 68 | + ) | ||
| 63 | return OverrideDefinitions( | 69 | return OverrideDefinitions( |
| 64 | override_args=[recipe + extra_override_imports + extra_args], | 70 | override_args=[recipe + extra_override_imports + extra_args], |
| 65 | train_args=V4_TRAIN_ARGS, | 71 | train_args=V4_TRAIN_ARGS, |
| @@ -328,13 +334,16 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 328 | test_name="dsv4_smla_cp2_ep2_fsdp2", | 334 | test_name="dsv4_smla_cp2_ep2_fsdp2", |
| 329 | test_descr="DeepSeek-V4 SMLA Muon cp2 ep2 fsdp2", | 335 | test_descr="DeepSeek-V4 SMLA Muon cp2 ep2 fsdp2", |
| 330 | ngpu=4, | 336 | ngpu=4, |
| 337 | + env_vars={ | ||
| 338 | + "MODULE": "tests.integration_tests.mtp_config", | ||
| 339 | + "CONFIG": "deepseek_v4_debugmodel_cp", | ||
| 340 | + "DSV4_PER_DOC_ALIGNMENT": "256", | ||
| 341 | + }, | ||
| 342 | + use_cp_attention=True, | ||
| 331 | extra_args=( | 343 | extra_args=( |
| 332 | "--training.steps=1", | 344 | "--training.steps=1", |
| 333 | "--parallelism.expert-parallel-degree=2", | 345 | "--parallelism.expert-parallel-degree=2", |
| 334 | "--parallelism.context-parallel-degree=2", | 346 | "--parallelism.context-parallel-degree=2", |
| 335 | - "--parallelism.context-parallel-load-balancer=None", | ||
| 336 | - "--parallelism.spmd-backend=spmd_types", | ||
| 337 | - "--dataloader.per_doc_alignment=256", | ||
| 338 | "--hf-assets-path=tests/assets/deepseek_v3", | 347 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 339 | "--training.num-tokens-per-train-step=4096", | 348 | "--training.num-tokens-per-train-step=4096", |
| 340 | "--optim.optimizer.name=Muon", | 349 | "--optim.optimizer.name=Muon", |
| @@ -349,18 +358,17 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 349 | ), | 358 | ), |
| 350 | _build_case( | 359 | _build_case( |
| 351 | test_name="dsv4_mtp_smla_cp2", | 360 | test_name="dsv4_mtp_smla_cp2", |
| 352 | - test_descr="DeepSeek-V4 MTP SMLA Muon cp2", | 361 | + test_descr="DeepSeek-V4 MTP SMLA AdamW cp2", |
| 353 | ngpu=2, | 362 | ngpu=2, |
| 354 | env_vars={ | 363 | env_vars={ |
| 355 | "MODULE": "tests.integration_tests.mtp_config", | 364 | "MODULE": "tests.integration_tests.mtp_config", |
| 356 | "CONFIG": "deepseek_v4_debugmodel_mtp", | 365 | "CONFIG": "deepseek_v4_debugmodel_mtp", |
| 366 | + "DSV4_PER_DOC_ALIGNMENT": "256", | ||
| 357 | }, | 367 | }, |
| 368 | + use_cp_attention=True, | ||
| 358 | extra_args=( | 369 | extra_args=( |
| 359 | "--training.steps=1", | 370 | "--training.steps=1", |
| 360 | "--parallelism.context-parallel-degree=2", | 371 | "--parallelism.context-parallel-degree=2", |
| 361 | - "--parallelism.context-parallel-load-balancer=None", | ||
| 362 | - "--parallelism.spmd-backend=spmd_types", | ||
| 363 | - "--dataloader.per_doc_alignment=256", | ||
| 364 | "--hf-assets-path=tests/assets/deepseek_v3", | 372 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 365 | "--training.num-tokens-per-train-step=4096", | 373 | "--training.num-tokens-per-train-step=4096", |
| 366 | "--optim.optimizer.name=Muon", | 374 | "--optim.optimizer.name=Muon", |
| @@ -3,16 +3,31 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 3 | # This source code is licensed under the BSD-style license found in the |
| 4 | # LICENSE file in the root directory of this source tree. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -"""Config module for the MTP x CP integration case. | 6 | +"""Debug recipes with the native typed V4 context-parallel backend.""" |
| 7 | 7 | ||
| 8 | -The runner's default config module is the model package and its default ``CONFIG`` is | 8 | +from torchtitan.config.transform import ContextParallelTransform |
| 9 | -``deepseek_v4_debugmodel``, whose ``num_mtp_layers`` is 0. This module is selected by the | ||
| 10 | -case's ``env_vars`` so the case named after MTP actually builds the MTP layers. | ||
| 11 | -""" | ||
| 12 | 9 | ||
| 13 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | 10 | from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel |
| 14 | 11 | ||
| 15 | 12 | ||
| 13 | +def _debugmodel_cp(*, num_mtp_layers: int): | ||
| 14 | + from torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc import AscV4ContextParallelSparseAttention | ||
| 15 | + | ||
| 16 | + config = deepseek_v4_debugmodel(num_mtp_layers=num_mtp_layers) | ||
| 17 | + transform = ContextParallelTransform(inner_attention=AscV4ContextParallelSparseAttention) | ||
| 18 | + config.model = transform.transform(config.model) | ||
| 19 | + for _, attention, _, _ in config.model.traverse(AscV4ContextParallelSparseAttention.Config): | ||
| 20 | + # Match the geometry of the fused debug recipe, including its MTP blocks. | ||
| 21 | + attention.num_heads = 16 | ||
| 22 | + attention.index_num_heads = 8 | ||
| 23 | + return config | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def deepseek_v4_debugmodel_cp(): | ||
| 27 | + """Debug model for the CP2 + EP2 smoke case.""" | ||
| 28 | + return _debugmodel_cp(num_mtp_layers=0) | ||
| 29 | + | ||
| 30 | + | ||
| 16 | def deepseek_v4_debugmodel_mtp(): | 31 | def deepseek_v4_debugmodel_mtp(): |
| 17 | - """The debug model with one MTP depth, for the MTP x CP case.""" | 32 | + """Debug model with one MTP depth for the CP2 smoke case.""" |
| 18 | - return deepseek_v4_debugmodel(num_mtp_layers=1) | 33 | + return _debugmodel_cp(num_mtp_layers=1) |
| @@ -5,7 +5,7 @@ import pytest | |||
| 5 | import torch | 5 | import torch |
| 6 | 6 | ||
| 7 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _build_model_config | 7 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _build_model_config |
| 8 | -from tests.unit_tests.models.test_deepseek_v4_mtp_model import _build_model_config as _compressed_config | 8 | +from tests.unit_tests.models.mtp_test_utils import build_v4_model_config |
| 9 | from torchtitan_npu.models.deepseek_v4.state_dict_adapter import DeepSeekV4StateDictAdapter | 9 | from torchtitan_npu.models.deepseek_v4.state_dict_adapter import DeepSeekV4StateDictAdapter |
| 10 | 10 | ||
| 11 | 11 | ||
| @@ -25,7 +25,7 @@ def test_sink_preserves_bare_parameter_shape_and_values(prefix): | |||
| 25 | 25 | ||
| 26 | 26 | ||
| 27 | def test_full_model_checkpoint_roundtrip_preserves_fused_experts_and_compressors(): | 27 | def test_full_model_checkpoint_roundtrip_preserves_fused_experts_and_compressors(): |
| 28 | - config = _compressed_config(compress_ratios=(1, 4, 128), rope_head_dim=8, original_seq_len=65536) | 28 | + config = build_v4_model_config(compress_ratios=(1, 4, 128), rope_head_dim=8, original_seq_len=65536) |
| 29 | with torch.device("meta"): | 29 | with torch.device("meta"): |
| 30 | model = config.build() | 30 | model = config.build() |
| 31 | state = { | 31 | state = { |
| @@ -83,3 +83,47 @@ def assert_packed_mtp_training(model) -> None: | |||
| 83 | loss.backward() | 83 | loss.backward() |
| 84 | if not any(parameter.grad is not None for parameter in model.mtp_layers.parameters()): | 84 | if not any(parameter.grad is not None for parameter in model.mtp_layers.parameters()): |
| 85 | raise AssertionError("Expected at least one MTP parameter to receive a gradient.") | 85 | raise AssertionError("Expected at least one MTP parameter to receive a gradient.") |
| 86 | + | ||
| 87 | + | ||
| 88 | +def build_v4_model_config( | ||
| 89 | + *, | ||
| 90 | + compress_ratios=(1, 1, 1), | ||
| 91 | + rope_head_dim=4, | ||
| 92 | + original_seq_len=SEQ_LEN, | ||
| 93 | + num_mtp_layers=1, | ||
| 94 | + n_hash_layers=0, | ||
| 95 | +): | ||
| 96 | + from torchtitan_npu.models.deepseek_v4 import _make_v4_config | ||
| 97 | + | ||
| 98 | + return _make_v4_config( | ||
| 99 | + dim=32, | ||
| 100 | + n_layers=3, | ||
| 101 | + vocab_size=VOCAB_SIZE, | ||
| 102 | + n_heads=4, | ||
| 103 | + head_dim=8, | ||
| 104 | + rope_head_dim=rope_head_dim, | ||
| 105 | + q_lora_rank=16, | ||
| 106 | + o_lora_rank=8, | ||
| 107 | + n_groups=2, | ||
| 108 | + compress_ratios=compress_ratios, | ||
| 109 | + window_size=SEQ_LEN, | ||
| 110 | + norm_eps=1e-6, | ||
| 111 | + index_n_heads=2, | ||
| 112 | + index_head_dim=8, | ||
| 113 | + index_topk=2, | ||
| 114 | + moe_inter_dim=16, | ||
| 115 | + num_experts=2, | ||
| 116 | + num_shared_experts=1, | ||
| 117 | + top_k=1, | ||
| 118 | + n_hash_layers=n_hash_layers, | ||
| 119 | + route_norm=False, | ||
| 120 | + route_scale=1.0, | ||
| 121 | + load_balance_coeff=1e-3, | ||
| 122 | + hc_mult=2, | ||
| 123 | + sinkhorn_iters=2, | ||
| 124 | + hc_eps=1e-6, | ||
| 125 | + max_seq_len=SEQ_LEN, | ||
| 126 | + compress_rope_theta=10000.0, | ||
| 127 | + original_seq_len=original_seq_len, | ||
| 128 | + num_mtp_layers=num_mtp_layers, | ||
| 129 | + ) | ||
| @@ -5,10 +5,15 @@ | |||
| 5 | # LICENSE file in the root directory of this source tree. | 5 | # LICENSE file in the root directory of this source tree. |
| 6 | 6 | ||
| 7 | from copy import deepcopy | 7 | from copy import deepcopy |
| 8 | +from inspect import signature | ||
| 9 | +from types import MethodType | ||
| 8 | 10 | ||
| 9 | import pytest | 11 | import pytest |
| 10 | import torch | 12 | import torch |
| 11 | from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss | 13 | from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss |
| 14 | +from torchtitan.models.deepseek_v3.mtp import MTPLoss | ||
| 15 | +from torchtitan.models.deepseek_v4.mtp import MTPBlock | ||
| 16 | +from torchtitan.protocols.module import ModuleList | ||
| 12 | 17 | ||
| 13 | from tests.unit_tests.models.mtp_test_utils import ( | 18 | from tests.unit_tests.models.mtp_test_utils import ( |
| 14 | PACKED_POSITIONS, | 19 | PACKED_POSITIONS, |
| @@ -16,11 +21,15 @@ from tests.unit_tests.models.mtp_test_utils import ( | |||
| 16 | VOCAB_SIZE, | 21 | VOCAB_SIZE, |
| 17 | assert_packed_mtp_training, | 22 | assert_packed_mtp_training, |
| 18 | build_cpu_model, | 23 | build_cpu_model, |
| 24 | + build_v4_model_config, | ||
| 19 | preprocess, | 25 | preprocess, |
| 20 | ) | 26 | ) |
| 21 | from torchtitan_npu.models.common.linear import SharedLinear | 27 | from torchtitan_npu.models.common.linear import SharedLinear |
| 22 | -from torchtitan_npu.models.deepseek_v4 import _make_v4_config | 28 | +from torchtitan_npu.models.deepseek_v4.config_registry import ( |
| 23 | -from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | 29 | + deepseek_v4_debugmodel, |
| 30 | + deepseek_v4_flash_43layers_16experts, | ||
| 31 | +) | ||
| 32 | +from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4TransformerBlock | ||
| 24 | from torchtitan_npu.models.deepseek_v4.mtp import MTPChunkedLossWrapper | 33 | from torchtitan_npu.models.deepseek_v4.mtp import MTPChunkedLossWrapper |
| 25 | from torchtitan_npu.models.deepseek_v4.state_dict_adapter import ( | 34 | from torchtitan_npu.models.deepseek_v4.state_dict_adapter import ( |
| 26 | DeepSeekV4StateDictAdapter, | 35 | DeepSeekV4StateDictAdapter, |
| @@ -29,54 +38,41 @@ from torchtitan_npu.models.deepseek_v4.state_dict_adapter import ( | |||
| 29 | pytestmark = pytest.mark.usefixtures("single_rank_spmd") | 38 | pytestmark = pytest.mark.usefixtures("single_rank_spmd") |
| 30 | 39 | ||
| 31 | 40 | ||
| 32 | -def _build_model_config( | 41 | +@pytest.mark.parametrize( |
| 33 | - *, | 42 | + "recipe", [deepseek_v4_debugmodel, deepseek_v4_flash_43layers_16experts], ids=["debug", "flash43"] |
| 34 | - compress_ratios=(1, 1, 1), | 43 | +) |
| 35 | - rope_head_dim=4, | 44 | +@pytest.mark.parametrize("num_mtp_layers", [0, 1, 2]) |
| 36 | - original_seq_len=SEQ_LEN, | 45 | +def test_v4_recipe_builds_upstream_mtp_contract(recipe, num_mtp_layers): |
| 37 | - num_mtp_layers=1, | 46 | + trainer_config = recipe(num_mtp_layers=num_mtp_layers) |
| 38 | -): | 47 | + model_config = trainer_config.model |
| 39 | - return _make_v4_config( | 48 | + if num_mtp_layers: |
| 40 | - dim=32, | 49 | + assert len(model_config.mtp_layers) == num_mtp_layers |
| 41 | - n_layers=3, | 50 | + assert all(type(layer) is MTPBlock.Config for layer in model_config.mtp_layers) |
| 42 | - vocab_size=VOCAB_SIZE, | 51 | + assert isinstance(trainer_config.loss, MTPChunkedLossWrapper.Config) |
| 43 | - n_heads=4, | 52 | + else: |
| 44 | - head_dim=8, | 53 | + assert model_config.mtp_layers == [] |
| 45 | - rope_head_dim=rope_head_dim, | 54 | + assert type(trainer_config.loss) is ChunkedLossWrapper.Config |
| 46 | - q_lora_rank=16, | 55 | + with torch.device("meta"): |
| 47 | - o_lora_rank=8, | 56 | + model = model_config.build() |
| 48 | - n_groups=2, | 57 | + assert isinstance(model.mtp_layers, ModuleList) |
| 49 | - compress_ratios=compress_ratios, | 58 | + assert len(model.mtp_layers) == num_mtp_layers |
| 50 | - window_size=SEQ_LEN, | 59 | + assert all(type(layer) is MTPBlock for layer in model.mtp_layers) |
| 51 | - norm_eps=1e-6, | 60 | + assert bool([name for name, _ in model.named_parameters() if name.startswith("mtp_layers.")]) == bool( |
| 52 | - index_n_heads=2, | 61 | + num_mtp_layers |
| 53 | - index_head_dim=8, | ||
| 54 | - index_topk=2, | ||
| 55 | - moe_inter_dim=16, | ||
| 56 | - num_experts=2, | ||
| 57 | - num_shared_experts=1, | ||
| 58 | - top_k=1, | ||
| 59 | - n_hash_layers=0, | ||
| 60 | - route_norm=False, | ||
| 61 | - route_scale=1.0, | ||
| 62 | - load_balance_coeff=1e-3, | ||
| 63 | - hc_mult=2, | ||
| 64 | - sinkhorn_iters=2, | ||
| 65 | - hc_eps=1e-6, | ||
| 66 | - max_seq_len=SEQ_LEN, | ||
| 67 | - compress_rope_theta=10000.0, | ||
| 68 | - original_seq_len=original_seq_len, | ||
| 69 | - num_mtp_layers=num_mtp_layers, | ||
| 70 | ) | 62 | ) |
| 71 | 63 | ||
| 72 | 64 | ||
| 65 | +def test_upstream_mtp_block_accepts_sequence_parallel_valid_mask(): | ||
| 66 | + assert "mtp_input_valid_mask" in signature(MTPBlock.forward).parameters | ||
| 67 | + | ||
| 68 | + | ||
| 73 | def test_deepseek_v4_mtp_model_supports_packed_sequences(): | 69 | def test_deepseek_v4_mtp_model_supports_packed_sequences(): |
| 74 | - assert_packed_mtp_training(build_cpu_model(_build_model_config())) | 70 | + assert_packed_mtp_training(build_cpu_model(build_v4_model_config())) |
| 75 | 71 | ||
| 76 | 72 | ||
| 77 | def test_deepseek_v4_mtp_metadata_includes_uncompressed_plan(): | 73 | def test_deepseek_v4_mtp_metadata_includes_uncompressed_plan(): |
| 78 | model = build_cpu_model( | 74 | model = build_cpu_model( |
| 79 | - _build_model_config( | 75 | + build_v4_model_config( |
| 80 | compress_ratios=(128, 128, 4), | 76 | compress_ratios=(128, 128, 4), |
| 81 | rope_head_dim=8, | 77 | rope_head_dim=8, |
| 82 | original_seq_len=65536, | 78 | original_seq_len=65536, |
| @@ -98,7 +94,7 @@ def test_deepseek_v4_mtp_metadata_includes_uncompressed_plan(): | |||
| 98 | 94 | ||
| 99 | 95 | ||
| 100 | def test_deepseek_v4_mtp_model_supports_chunked_loss(): | 96 | def test_deepseek_v4_mtp_model_supports_chunked_loss(): |
| 101 | - model = build_cpu_model(_build_model_config()) | 97 | + model = build_cpu_model(build_v4_model_config()) |
| 102 | tokens = torch.arange(SEQ_LEN) % VOCAB_SIZE | 98 | tokens = torch.arange(SEQ_LEN) % VOCAB_SIZE |
| 103 | positions = PACKED_POSITIONS.clone() | 99 | positions = PACKED_POSITIONS.clone() |
| 104 | labels = (tokens + 1) % VOCAB_SIZE | 100 | labels = (tokens + 1) % VOCAB_SIZE |
| @@ -178,7 +174,7 @@ def test_deepseek_v4_mtp_isolation_rejects_incompatible_loss_head(missing_head): | |||
| 178 | 174 | ||
| 179 | def test_deepseek_v4_mtp_isolation_rejects_replaced_model_head(): | 175 | def test_deepseek_v4_mtp_isolation_rejects_replaced_model_head(): |
| 180 | with torch.random.fork_rng(): | 176 | with torch.random.fork_rng(): |
| 181 | - config = _build_model_config() | 177 | + config = build_v4_model_config() |
| 182 | config.mtp_isolate_gradients = True | 178 | config.mtp_isolate_gradients = True |
| 183 | model = build_cpu_model(config) | 179 | model = build_cpu_model(config) |
| 184 | model.lm_head = torch.nn.Linear(32, VOCAB_SIZE, bias=False) | 180 | model.lm_head = torch.nn.Linear(32, VOCAB_SIZE, bias=False) |
| @@ -192,7 +188,7 @@ def test_deepseek_v4_mtp_isolation_rejects_replaced_model_head(): | |||
| 192 | @pytest.mark.parametrize("num_mtp_layers", [1, 2], ids=["depth1", "depth2"]) | 188 | @pytest.mark.parametrize("num_mtp_layers", [1, 2], ids=["depth1", "depth2"]) |
| 193 | def test_deepseek_v4_mtp_detaches_all_shared_parameters(num_mtp_layers): | 189 | def test_deepseek_v4_mtp_detaches_all_shared_parameters(num_mtp_layers): |
| 194 | with torch.random.fork_rng(): | 190 | with torch.random.fork_rng(): |
| 195 | - config = _build_model_config(num_mtp_layers=num_mtp_layers) | 191 | + config = build_v4_model_config(num_mtp_layers=num_mtp_layers) |
| 196 | config.mtp_isolate_gradients = True | 192 | config.mtp_isolate_gradients = True |
| 197 | model = build_cpu_model(config) | 193 | model = build_cpu_model(config) |
| 198 | tokens = torch.arange(SEQ_LEN) % VOCAB_SIZE | 194 | tokens = torch.arange(SEQ_LEN) % VOCAB_SIZE |
| @@ -214,7 +210,7 @@ def test_deepseek_v4_mtp_detaches_all_shared_parameters(num_mtp_layers): | |||
| 214 | @pytest.mark.parametrize("chunked", [False, True], ids=["logits", "chunked"]) | 210 | @pytest.mark.parametrize("chunked", [False, True], ids=["logits", "chunked"]) |
| 215 | def test_deepseek_v4_mtp_isolation_preserves_main_gradients(chunked, single_threaded_cpu): | 211 | def test_deepseek_v4_mtp_isolation_preserves_main_gradients(chunked, single_threaded_cpu): |
| 216 | with torch.random.fork_rng(): | 212 | with torch.random.fork_rng(): |
| 217 | - config = _build_model_config() | 213 | + config = build_v4_model_config() |
| 218 | reference = build_cpu_model(config) | 214 | reference = build_cpu_model(config) |
| 219 | isolated_config = deepcopy(config) | 215 | isolated_config = deepcopy(config) |
| 220 | isolated_config.mtp_isolate_gradients = True | 216 | isolated_config.mtp_isolate_gradients = True |
| @@ -256,12 +252,12 @@ def test_deepseek_v4_mtp_isolation_preserves_main_gradients(chunked, single_thre | |||
| 256 | assert (parameter.grad is None) == (expected_grad is None), name | 252 | assert (parameter.grad is None) == (expected_grad is None), name |
| 257 | if expected_grad is not None: | 253 | if expected_grad is not None: |
| 258 | torch.testing.assert_close( | 254 | torch.testing.assert_close( |
| 259 | - parameter.grad, expected_grad, rtol=0, atol=0, msg=lambda message: f"{name}: {message}" | 255 | + parameter.grad, expected_grad, rtol=0, atol=0, msg=lambda message, name=name: f"{name}: {message}" |
| 260 | ) | 256 | ) |
| 261 | 257 | ||
| 262 | 258 | ||
| 263 | def test_deepseek_v4_mtp_state_dict_round_trip(): | 259 | def test_deepseek_v4_mtp_state_dict_round_trip(): |
| 264 | - model_config = _build_model_config() | 260 | + model_config = build_v4_model_config() |
| 265 | model = build_cpu_model(model_config) | 261 | model = build_cpu_model(model_config) |
| 266 | local_state_dict = { | 262 | local_state_dict = { |
| 267 | key: value.detach().clone() for key, value in model.state_dict().items() if key.startswith("mtp_layers.0.") | 263 | key: value.detach().clone() for key, value in model.state_dict().items() if key.startswith("mtp_layers.0.") |
| @@ -313,113 +309,178 @@ def test_deepseek_v4_mtp_state_dict_round_trip(): | |||
| 313 | ), | 309 | ), |
| 314 | ) | 310 | ) |
| 315 | def test_deepseek_v4_mtp_state_dict_rejects_invalid_depth(method_name, key): | 311 | def test_deepseek_v4_mtp_state_dict_rejects_invalid_depth(method_name, key): |
| 316 | - model_config = _build_model_config() | 312 | + model_config = build_v4_model_config() |
| 317 | adapter = DeepSeekV4StateDictAdapter(model_config, hf_assets_path=None) | 313 | adapter = DeepSeekV4StateDictAdapter(model_config, hf_assets_path=None) |
| 318 | 314 | ||
| 319 | with pytest.raises(ValueError, match="not present"): | 315 | with pytest.raises(ValueError, match="not present"): |
| 320 | getattr(adapter, method_name)({key: torch.ones(1)}) | 316 | getattr(adapter, method_name)({key: torch.ones(1)}) |
| 321 | 317 | ||
| 322 | 318 | ||
| 323 | -def test_preprocess_inputs_builds_the_mtp_batch_on_the_global_row(monkeypatch): | 319 | +@pytest.mark.parametrize("rank", [0, 1]) |
| 324 | - """The MTP depths' rolled tokens are built before the CP shard, then cut with it. | 320 | +def test_preprocess_mtp_batch_uses_the_main_input_cp_layout(monkeypatch, rank, single_rank_spmd): |
| 325 | - | ||
| 326 | - A shift across a shard boundary is not a shift, so the batch must be built | ||
| 327 | - from the whole row and the same ``cp_shard`` cut applied afterwards. The | ||
| 328 | - shard here really slices rank 1's half of a two-rank run, so the test pins | ||
| 329 | - the alignment, not only the call order. | ||
| 330 | - """ | ||
| 331 | from types import SimpleNamespace | 321 | from types import SimpleNamespace |
| 332 | 322 | ||
| 333 | - from torchtitan_npu.models.deepseek_v4 import model as model_mod | 323 | + from torchtitan.config.parallelism import ParallelismConfig |
| 324 | + from torchtitan.distributed import context_parallel | ||
| 334 | 325 | ||
| 335 | - model = build_cpu_model(_build_model_config()) | 326 | + from torchtitan_npu.models.deepseek_v4.metadata import DeepSeekV4Metadata, doc_chunk_entry |
| 336 | - tokens = torch.arange(SEQ_LEN) % VOCAB_SIZE | 327 | + from torchtitan_npu.patches.torchtitan.distributed import context_parallel as cp_patch |
| 337 | - labels = (tokens + 1) % VOCAB_SIZE | 328 | + |
| 329 | + with torch.random.fork_rng(): | ||
| 330 | + model = build_cpu_model(build_v4_model_config(num_mtp_layers=2)) | ||
| 331 | + tokens = torch.arange(SEQ_LEN) | ||
| 332 | + labels = tokens + 1000 | ||
| 338 | positions = PACKED_POSITIONS.clone() | 333 | positions = PACKED_POSITIONS.clone() |
| 339 | - | ||
| 340 | - real_prepare = model_mod.prepare_mtp_batch | ||
| 341 | - built = [] | ||
| 342 | - | ||
| 343 | - def record_prepare(inputs, prepared_labels, prepared_positions, num_layers): | ||
| 344 | - batch = real_prepare(inputs, prepared_labels, prepared_positions, num_layers) | ||
| 345 | - built.append((inputs, prepared_labels, prepared_positions, batch)) | ||
| 346 | - return batch | ||
| 347 | - | ||
| 348 | shard_calls = [] | 334 | shard_calls = [] |
| 349 | - rank, cp_size = 1, 2 | 335 | + mesh = SimpleNamespace(size=lambda *_: 2, get_local_rank=lambda: rank, device_type="cpu") |
| 350 | - shard_len = SEQ_LEN // cp_size | 336 | + indices = torch.cat( |
| 351 | - | 337 | + [torch.arange(rank * 64, (rank + 1) * 64), torch.arange(128 + rank * 64, 128 + (rank + 1) * 64)] |
| 352 | - def fake_cp_shard(input_dict, *, input_shardings, parallelism_context, parallelism): | ||
| 353 | - shard_calls.append((dict(input_dict), input_dict["positions"], input_shardings)) | ||
| 354 | - assert parallelism_context.get_mesh("cp") is mesh | ||
| 355 | - return {key: tensor.narrow(0, rank * shard_len, shard_len) for key, tensor in input_dict.items()} | ||
| 356 | - | ||
| 357 | - monkeypatch.setattr(model_mod, "prepare_mtp_batch", record_prepare) | ||
| 358 | - monkeypatch.setattr(model, "_cp_shard", fake_cp_shard) | ||
| 359 | - | ||
| 360 | - # Isolate the decoder's metadata build; both calls still exercise the model's named shard boundary. | ||
| 361 | - from torchtitan.models.common.decoder import Decoder | ||
| 362 | - from torchtitan.models.common.decoder_sharding import decoder_input_sharding | ||
| 363 | - | ||
| 364 | - from torchtitan_npu.models.deepseek_v4.metadata import build_v4_metadata, doc_chunk_entry | ||
| 365 | - | ||
| 366 | - base_calls = [] | ||
| 367 | - row_entry = build_v4_metadata(positions, 1) | ||
| 368 | - local_entry = doc_chunk_entry(row_entry, cp_size=cp_size, cp_rank=rank, slab_len=shard_len) | ||
| 369 | - | ||
| 370 | - def fake_base(self, input_dict, *, parallelism_context, parallelism, **kwargs): | ||
| 371 | - del kwargs | ||
| 372 | - base_calls.append((input_dict["input"].shape, input_dict["labels"].shape)) | ||
| 373 | - cut = self._cp_shard( | ||
| 374 | - input_dict, | ||
| 375 | - input_shardings=decoder_input_sharding(), | ||
| 376 | - parallelism_context=parallelism_context, | ||
| 377 | - parallelism=parallelism, | ||
| 378 | - ) | ||
| 379 | - return ( | ||
| 380 | - cut["input"], | ||
| 381 | - cut["labels"], | ||
| 382 | - {"positions": cut["positions"], "attention_metadata": {("debug", 1): local_entry}}, | ||
| 383 | - ) | ||
| 384 | - | ||
| 385 | - monkeypatch.setattr(Decoder, "preprocess_inputs", fake_base) | ||
| 386 | - mesh = SimpleNamespace(size=lambda *_: cp_size, get_local_rank=lambda: rank, device_type="cpu") | ||
| 387 | - parallelism_context = SimpleNamespace(cp_enabled=True, get_mesh=lambda name: mesh) | ||
| 388 | - parallelism = SimpleNamespace(context_parallel_load_balancer=None) | ||
| 389 | - inputs, out_labels, extra_kwargs = model.preprocess_inputs( | ||
| 390 | - {"input": tokens, "labels": labels, "positions": positions}, | ||
| 391 | - parallelism_context=parallelism_context, | ||
| 392 | - parallelism=parallelism, | ||
| 393 | ) | 338 | ) |
| 394 | 339 | ||
| 395 | - # The batch was built from the global row, once. | 340 | + def device_shard(batch, *, input_shardings, permutation): |
| 396 | - assert len(built) == 1 | 341 | + assert permutation is not None |
| 397 | - global_inputs, global_labels, global_positions, batch = built[0] | 342 | + permutation = permutation.flatten() |
| 398 | - assert global_inputs.shape == tokens.shape | 343 | + shard_calls.append((set(input_shardings) & batch.keys(), permutation)) |
| 399 | - assert torch.equal(global_labels, labels) | 344 | + return { |
| 400 | - assert torch.equal(global_positions, positions) | 345 | + key: value.index_select(0, permutation).chunk(mesh.size(), dim=0)[rank] if key in input_shardings else value |
| 346 | + for key, value in batch.items() | ||
| 347 | + } | ||
| 401 | 348 | ||
| 402 | - # Two cuts, both fed the full row: the base inputs, then the MTP batch. | 349 | + def cpu_metadata(entry, *, permutation): |
| 403 | - assert base_calls == [(tokens.shape, labels.shape)] | 350 | + del permutation |
| 404 | - assert len(shard_calls) == 2 | 351 | + return doc_chunk_entry(entry, cp_size=2, cp_rank=rank, slab_len=SEQ_LEN // 2) |
| 405 | - for name, expected in (("input", tokens), ("labels", labels), ("positions", positions)): | ||
| 406 | - assert torch.equal(shard_calls[0][0][name], expected) | ||
| 407 | - for index, expected in enumerate(batch): | ||
| 408 | - assert torch.equal(shard_calls[1][0][f"mtp_{index}"], expected) | ||
| 409 | - # The row reaches both calls, so the layout cannot be derived from anything else. | ||
| 410 | - for _, handed_positions, _ in shard_calls: | ||
| 411 | - assert torch.equal(handed_positions, positions) | ||
| 412 | - # Every MTP tensor uses the same token layout that the decoder's native shard consumes. | ||
| 413 | - assert set(shard_calls[1][2]) == {"mtp_0", "mtp_1", "mtp_2", "positions"} | ||
| 414 | - assert all(layout == decoder_input_sharding()["input"] for layout in shard_calls[1][2].values()) | ||
| 415 | 352 | ||
| 416 | - # What the forward reads is the shard's answer, not the global row. | 353 | + monkeypatch.setattr(DeepSeekV4Metadata, "prepare_cp_metadata", staticmethod(cpu_metadata)) |
| 417 | - slab = slice(rank * shard_len, (rank + 1) * shard_len) | 354 | + monkeypatch.setattr(cp_patch, "spmd_mesh_group", lambda name: mesh) |
| 418 | - assert torch.equal(inputs, tokens[slab]) and torch.equal(out_labels, labels[slab]) | 355 | + monkeypatch.setattr(context_parallel, "shard_tensors", device_shard) |
| 419 | - assert torch.equal(extra_kwargs["positions"], positions[slab]) | 356 | + inputs, out_labels, extra = model.preprocess_inputs( |
| 420 | - # The mask is the global row's own (a shift across a shard boundary is not a shift): the | 357 | + {"input": tokens, "labels": labels, "positions": positions}, |
| 421 | - # local copy is exactly its slab, so the row's last token still has no successor. | 358 | + parallelism_context=SimpleNamespace( |
| 422 | - local_batch = extra_kwargs["mtp_batch"] | 359 | + cp_enabled=True, get_mesh=lambda name: mesh, spmd_dense_mesh=single_rank_spmd.spmd_dense_mesh |
| 423 | - assert torch.equal(local_batch.input_valid_mask, batch.input_valid_mask[slab]) | 360 | + ), |
| 424 | - assert not bool(local_batch.input_valid_mask[-1].all()) | 361 | + parallelism=ParallelismConfig(context_parallel_load_balancer=None), |
| 425 | - assert extra_kwargs["attention_metadata"][("debug", 1)] is local_entry | 362 | + ) |
| 363 | + assert [keys for keys, _ in shard_calls] == [ | ||
| 364 | + {"input", "labels", "positions"}, | ||
| 365 | + {"mtp_0", "mtp_1", "mtp_2", "positions"}, | ||
| 366 | + ] | ||
| 367 | + torch.testing.assert_close(shard_calls[0][1], shard_calls[1][1]) | ||
| 368 | + batch = extra["mtp_batch"] | ||
| 369 | + torch.testing.assert_close(inputs, tokens[indices]) | ||
| 370 | + torch.testing.assert_close(out_labels, labels[indices]) | ||
| 371 | + torch.testing.assert_close(extra["positions"], positions[indices]) | ||
| 372 | + for depth in (1, 2): | ||
| 373 | + valid = indices.remainder(128) < 128 - depth | ||
| 374 | + torch.testing.assert_close(batch.input_tokens[..., depth - 1], torch.where(valid, indices + depth, 0)) | ||
| 375 | + torch.testing.assert_close(batch.input_valid_mask[..., depth - 1], valid) | ||
| 376 | + torch.testing.assert_close(batch.labels[..., depth - 1], torch.where(valid, indices + depth + 1000, -100)) | ||
| 377 | + | ||
| 378 | + | ||
| 379 | +# Reference computation from dev_0.4.0 commit 029756d, before upstream-block reuse. | ||
| 380 | +# Keep the two original computation paths independent of the inherited forward methods. | ||
| 381 | +def _baseline_v4_block_forward(self, hidden, input_ids, metadata, positions=None, *, padding_mask=None): | ||
| 382 | + residual = hidden | ||
| 383 | + hidden, post, comb = self.hc_attn_pre(hidden) | ||
| 384 | + hidden = self.attention(self.attention_norm(hidden), metadata, positions) | ||
| 385 | + hidden = self.hc_post(hidden, residual, post, comb) | ||
| 386 | + residual = hidden | ||
| 387 | + hidden, post, comb = self.hc_ffn_pre(hidden) | ||
| 388 | + hidden = self.moe(self.ffn_norm(hidden), input_ids_T=input_ids, padding_mask_T=padding_mask) | ||
| 389 | + return self.hc_post(hidden, residual, post, comb) | ||
| 390 | + | ||
| 391 | + | ||
| 392 | +def _baseline_mtp_forward( | ||
| 393 | + self, embedding, prev_hidden, input_ids, valid_mask, metadata, positions=None, *, padding_mask=None | ||
| 394 | +): | ||
| 395 | + prev_hidden = prev_hidden * valid_mask.unsqueeze(-1).unsqueeze(-1).to(prev_hidden.dtype) | ||
| 396 | + hidden = self.e_proj(self.enorm(embedding)).unsqueeze(1) + self.h_proj(self.hnorm(prev_hidden)) | ||
| 397 | + mtp_padding_mask = ~valid_mask if padding_mask is None else ~valid_mask | padding_mask | ||
| 398 | + next_hidden = _baseline_v4_block_forward( | ||
| 399 | + self, hidden, input_ids, metadata, positions, padding_mask=mtp_padding_mask | ||
| 400 | + ) | ||
| 401 | + prediction = self.mtp_norm(self.hc_head(next_hidden)) | ||
| 402 | + return next_hidden, prediction | ||
| 403 | + | ||
| 404 | + | ||
| 405 | +@pytest.mark.parametrize( | ||
| 406 | + ("chunked", "isolate", "prepared", "n_hash_layers", "num_mtp_layers"), | ||
| 407 | + [ | ||
| 408 | + (False, False, True, 0, 2), | ||
| 409 | + (True, False, False, 2, 2), | ||
| 410 | + (True, True, False, 0, 2), | ||
| 411 | + (True, False, True, 0, 2), | ||
| 412 | + (False, False, False, 2, 0), | ||
| 413 | + ], | ||
| 414 | + ids=["logits-learned", "chunked-hash", "chunked-isolated", "chunked-prepared-labels", "mtp-disabled"], | ||
| 415 | +) | ||
| 416 | +def test_upstream_mtp_block_matches_baseline_outputs_loss_and_gradients( | ||
| 417 | + chunked, isolate, prepared, n_hash_layers, num_mtp_layers, single_threaded_cpu | ||
| 418 | +): | ||
| 419 | + with torch.random.fork_rng(): | ||
| 420 | + config = build_v4_model_config(num_mtp_layers=num_mtp_layers, n_hash_layers=n_hash_layers) | ||
| 421 | + config.mtp_isolate_gradients = isolate | ||
| 422 | + model = build_cpu_model(config) | ||
| 423 | + reference = deepcopy(model) | ||
| 424 | + assert all(isinstance(layer, DeepSeekV4TransformerBlock) for layer in model.layers.values()) | ||
| 425 | + assert all(type(layer) is MTPBlock for layer in model.mtp_layers or ()) | ||
| 426 | + for layer in reference.layers.values(): | ||
| 427 | + layer.forward = MethodType(_baseline_v4_block_forward, layer) | ||
| 428 | + for layer in reference.mtp_layers or (): | ||
| 429 | + layer.forward = MethodType(_baseline_mtp_forward, layer) | ||
| 430 | + model._skip_lm_head = reference._skip_lm_head = chunked | ||
| 431 | + tokens = torch.arange(SEQ_LEN) % VOCAB_SIZE | ||
| 432 | + labels = (tokens + 1) % VOCAB_SIZE | ||
| 433 | + inputs, labels, extra_kwargs = preprocess(model, tokens, labels, PACKED_POSITIONS.clone()) | ||
| 434 | + if not prepared: | ||
| 435 | + extra_kwargs.pop("mtp_batch", None) | ||
| 436 | + | ||
| 437 | + actual_outputs = model(inputs, **extra_kwargs) | ||
| 438 | + expected_outputs = reference(inputs, **extra_kwargs) | ||
| 439 | + actual_branches = [actual_outputs] if isinstance(actual_outputs, torch.Tensor) else actual_outputs | ||
| 440 | + expected_branches = [expected_outputs] if isinstance(expected_outputs, torch.Tensor) else expected_outputs | ||
| 441 | + for actual, expected in zip(actual_branches, expected_branches, strict=True): | ||
| 442 | + torch.testing.assert_close(actual, expected, rtol=0, atol=0) | ||
| 443 | + if chunked: | ||
| 444 | + loss_config = MTPChunkedLossWrapper.Config( | ||
| 445 | + num_chunks=2, | ||
| 446 | + mtp_isolate_gradients=isolate, | ||
| 447 | + loss_fn=CrossEntropyLoss.Config(global_vocab_size=VOCAB_SIZE), | ||
| 448 | + ) | ||
| 449 | + actual_fn = loss_config.build() | ||
| 450 | + expected_fn = deepcopy(loss_config).build() | ||
| 451 | + actual_fn.set_lm_head(model.lm_head) | ||
| 452 | + expected_fn.set_lm_head(reference.lm_head) | ||
| 453 | + elif num_mtp_layers: | ||
| 454 | + actual_fn = MTPLoss(MTPLoss.Config(global_vocab_size=VOCAB_SIZE)) | ||
| 455 | + expected_fn = MTPLoss(MTPLoss.Config(global_vocab_size=VOCAB_SIZE)) | ||
| 456 | + else: | ||
| 457 | + actual_fn = CrossEntropyLoss(CrossEntropyLoss.Config(global_vocab_size=VOCAB_SIZE)) | ||
| 458 | + expected_fn = CrossEntropyLoss(CrossEntropyLoss.Config(global_vocab_size=VOCAB_SIZE)) | ||
| 459 | + denominator = torch.tensor(labels.numel()) | ||
| 460 | + if chunked: | ||
| 461 | + actual_loss, _ = actual_fn(actual_outputs, labels, denominator, positions=PACKED_POSITIONS) | ||
| 462 | + expected_loss, _ = expected_fn(expected_outputs, labels, denominator, positions=PACKED_POSITIONS) | ||
| 463 | + elif num_mtp_layers: | ||
| 464 | + aligned_labels = (labels, *extra_kwargs["mtp_batch"].labels.unbind(dim=-1)) | ||
| 465 | + actual_loss, _ = actual_fn(tuple(actual_outputs), aligned_labels, denominator) | ||
| 466 | + expected_loss, _ = expected_fn(tuple(expected_outputs), aligned_labels, denominator) | ||
| 467 | + else: | ||
| 468 | + actual_loss, _ = actual_fn(actual_outputs, labels, denominator) | ||
| 469 | + expected_loss, _ = expected_fn(expected_outputs, labels, denominator) | ||
| 470 | + actual_loss.backward() | ||
| 471 | + expected_loss.backward() | ||
| 472 | + | ||
| 473 | + torch.testing.assert_close(actual_loss, expected_loss, rtol=0, atol=0) | ||
| 474 | + expected_parameters = dict(reference.named_parameters()) | ||
| 475 | + assert dict(model.named_parameters()).keys() == expected_parameters.keys() | ||
| 476 | + for name, parameter in model.named_parameters(): | ||
| 477 | + expected_grad = expected_parameters[name].grad | ||
| 478 | + assert (parameter.grad is None) == (expected_grad is None), name | ||
| 479 | + if expected_grad is not None: | ||
| 480 | + torch.testing.assert_close( | ||
| 481 | + parameter.grad, | ||
| 482 | + expected_grad, | ||
| 483 | + rtol=0, | ||
| 484 | + atol=0, | ||
| 485 | + msg=lambda message, name=name: f"{name}: {message}", | ||
| 486 | + ) | ||
| @@ -18,38 +18,12 @@ from torchtitan_npu.models.deepseek_v3_2.config_registry import ( | |||
| 18 | from torchtitan_npu.models.deepseek_v4.config_registry import ( | 18 | from torchtitan_npu.models.deepseek_v4.config_registry import ( |
| 19 | deepseek_v4_debugmodel, | 19 | deepseek_v4_debugmodel, |
| 20 | ) | 20 | ) |
| 21 | -from torchtitan_npu.models.deepseek_v4.mtp import ( | 21 | +from torchtitan_npu.models.deepseek_v4.mtp import MTPChunkedLossWrapper, MTPModelOutput, prepare_mtp_batch |
| 22 | - MTPChunkedLossWrapper, | ||
| 23 | - MTPModelOutput, | ||
| 24 | - prepare_mtp_batch, | ||
| 25 | -) | ||
| 26 | 22 | ||
| 27 | _community_loss = import_module("torchtitan.components.loss") | 23 | _community_loss = import_module("torchtitan.components.loss") |
| 28 | _community_mtp = import_module("torchtitan.models.deepseek_v3.mtp") | 24 | _community_mtp = import_module("torchtitan.models.deepseek_v3.mtp") |
| 29 | 25 | ||
| 30 | 26 | ||
| 31 | -def test_dsv4_mtp_batch_precedes_cp_sharding(): | ||
| 32 | - tokens = torch.arange(8) | ||
| 33 | - labels = tokens + 1 | ||
| 34 | - positions = torch.arange(8) | ||
| 35 | - | ||
| 36 | - batch = prepare_mtp_batch(tokens, labels, positions, num_mtp_layers=1) | ||
| 37 | - | ||
| 38 | - # One head-tail CP rank owns disjoint prefix and suffix pieces. Selecting | ||
| 39 | - # from the globally shifted tensor preserves the future token at index 1; | ||
| 40 | - # rolling the already-local tensor would incorrectly select token 6. | ||
| 41 | - local_indices = torch.tensor([0, 1, 6, 7]) | ||
| 42 | - prepared_local = batch.input_tokens[local_indices, 0] | ||
| 43 | - incorrectly_rolled_local = _community_mtp.roll_mtp_sequence( | ||
| 44 | - tokens[local_indices], | ||
| 45 | - shift=1, | ||
| 46 | - fill_value=0, | ||
| 47 | - ) | ||
| 48 | - | ||
| 49 | - torch.testing.assert_close(prepared_local, torch.tensor([1, 2, 7, 0])) | ||
| 50 | - assert prepared_local[1] != incorrectly_rolled_local[1] | ||
| 51 | - | ||
| 52 | - | ||
| 53 | def test_dsv32_default_config_disables_mtp(): | 27 | def test_dsv32_default_config_disables_mtp(): |
| 54 | config = deepseek_v3_2_debugmodel() | 28 | config = deepseek_v3_2_debugmodel() |
| 55 | 29 | ||
| @@ -90,7 +64,7 @@ def test_dsv32_mtp_keeps_community_cp_restriction(): | |||
| 90 | 64 | ||
| 91 | 65 | ||
| 92 | def test_dsv4_mtp_accepts_cp_configuration(): | 66 | def test_dsv4_mtp_accepts_cp_configuration(): |
| 93 | - config = deepseek_v4_debugmodel() | 67 | + config = deepseek_v4_debugmodel(num_mtp_layers=1) |
| 94 | # A CP run splits every document into equal chunks and each chunk must stay | 68 | # A CP run splits every document into equal chunks and each chunk must stay |
| 95 | # ratio-aligned, so the loader's per-document alignment grows with the degree. | 69 | # ratio-aligned, so the loader's per-document alignment grows with the degree. |
| 96 | config.dataloader.dataset.dataset.processor.per_doc_alignment = 256 | 70 | config.dataloader.dataset.dataset.processor.per_doc_alignment = 256 |
| @@ -106,54 +80,12 @@ def test_prepare_mtp_batch_respects_packed_sequence_boundaries(): | |||
| 106 | tokens = torch.arange(10, 18) | 80 | tokens = torch.arange(10, 18) |
| 107 | labels = tokens + 100 | 81 | labels = tokens + 100 |
| 108 | positions = torch.tensor([0, 1, 2, 0, 1, 0, 1, 2]) | 82 | positions = torch.tensor([0, 1, 2, 0, 1, 0, 1, 2]) |
| 109 | - | ||
| 110 | batch = prepare_mtp_batch(tokens, labels, positions, num_mtp_layers=2) | 83 | batch = prepare_mtp_batch(tokens, labels, positions, num_mtp_layers=2) |
| 111 | - | 84 | + expected_tokens = (torch.tensor([11, 12, 0, 14, 0, 16, 17, 0]), torch.tensor([12, 0, 0, 0, 0, 17, 0, 0])) |
| 112 | - expected_tokens = torch.tensor( | 85 | + for depth, expected in enumerate(expected_tokens): |
| 113 | - [ | 86 | + torch.testing.assert_close(batch.input_tokens[..., depth], expected) |
| 114 | - [11, 12], | 87 | + torch.testing.assert_close(batch.input_valid_mask[..., depth], expected.ne(0)) |
| 115 | - [12, 0], | 88 | + torch.testing.assert_close(batch.labels[..., depth], torch.where(expected.ne(0), expected + 100, -100)) |
| 116 | - [0, 0], | ||
| 117 | - [14, 0], | ||
| 118 | - [0, 0], | ||
| 119 | - [16, 17], | ||
| 120 | - [17, 0], | ||
| 121 | - [0, 0], | ||
| 122 | - ] | ||
| 123 | - ) | ||
| 124 | - expected_valid = expected_tokens.ne(0) | ||
| 125 | - expected_labels = torch.where( | ||
| 126 | - expected_valid, | ||
| 127 | - expected_tokens + 100, | ||
| 128 | - _community_loss.IGNORE_INDEX, | ||
| 129 | - ) | ||
| 130 | - | ||
| 131 | - torch.testing.assert_close(batch.input_tokens, expected_tokens) | ||
| 132 | - torch.testing.assert_close(batch.input_valid_mask, expected_valid) | ||
| 133 | - torch.testing.assert_close(batch.labels, expected_labels) | ||
| 134 | - | ||
| 135 | - | ||
| 136 | -def test_prepared_mtp_labels_match_community_roll(): | ||
| 137 | - seq_len = 8 | ||
| 138 | - labels = torch.arange(seq_len) | ||
| 139 | - positions = torch.arange(seq_len) | ||
| 140 | - tokens = torch.zeros(seq_len, dtype=torch.long) | ||
| 141 | - | ||
| 142 | - mtp_batch = prepare_mtp_batch(tokens, labels, positions, num_mtp_layers=2) | ||
| 143 | - expected = torch.stack( | ||
| 144 | - [ | ||
| 145 | - _community_mtp.roll_mtp_sequence( | ||
| 146 | - labels, | ||
| 147 | - shift=depth, | ||
| 148 | - positions=positions, | ||
| 149 | - fill_value=_community_loss.IGNORE_INDEX, | ||
| 150 | - ) | ||
| 151 | - for depth in (1, 2) | ||
| 152 | - ], | ||
| 153 | - dim=-1, | ||
| 154 | - ) | ||
| 155 | - | ||
| 156 | - torch.testing.assert_close(mtp_batch.labels, expected, rtol=0, atol=0) | ||
| 157 | 89 | ||
| 158 | 90 | ||
| 159 | @dataclasses.dataclass(frozen=True) | 91 | @dataclasses.dataclass(frozen=True) |
| @@ -227,12 +159,7 @@ def _run_chunked_mtp_loss(case: _MTPChunkedLossCase) -> torch.Tensor: | |||
| 227 | loss, _ = loss_fn( | 159 | loss, _ = loss_fn( |
| 228 | MTPModelOutput( | 160 | MTPModelOutput( |
| 229 | case.hidden, | 161 | case.hidden, |
| 230 | - mtp_labels=prepare_mtp_batch( | 162 | + mtp_labels=prepare_mtp_batch(case.tokens, case.labels, case.positions, num_mtp_layers=2).labels, |
| 231 | - case.tokens, | ||
| 232 | - case.labels, | ||
| 233 | - case.positions, | ||
| 234 | - num_mtp_layers=2, | ||
| 235 | - ).labels, | ||
| 236 | ), | 163 | ), |
| 237 | case.labels, | 164 | case.labels, |
| 238 | case.global_valid_tokens, | 165 | case.global_valid_tokens, |
| @@ -22,6 +22,7 @@ from torchtitan.models.common.linear import RouterGateLinear | |||
| 22 | from torchtitan.models.common.moe import MoE | 22 | from torchtitan.models.common.moe import MoE |
| 23 | from torchtitan.models.common.param_init import depth_scaled_std | 23 | from torchtitan.models.common.param_init import depth_scaled_std |
| 24 | from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router | 24 | from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router |
| 25 | +from torchtitan.models.deepseek_v4.mtp import MTPBlock | ||
| 25 | 26 | ||
| 26 | from torchtitan_npu.models.common.carry_exchange import CarryExchange | 27 | from torchtitan_npu.models.common.carry_exchange import CarryExchange |
| 27 | from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear | 28 | from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear |
| @@ -33,16 +34,10 @@ from .model import ( | |||
| 33 | DeepSeekV4Model, | 34 | DeepSeekV4Model, |
| 34 | DeepSeekV4TransformerBlock, | 35 | DeepSeekV4TransformerBlock, |
| 35 | ) | 36 | ) |
| 36 | -from .mtp import ( | 37 | +from .mtp import MTPLoss |
| 37 | - DeepSeekV4MTPDecoder, | ||
| 38 | - DeepSeekV4MTPTransformerBlock, | ||
| 39 | - MTPLoss, | ||
| 40 | -) | ||
| 41 | from .state_dict_adapter import DeepSeekV4StateDictAdapter | 38 | from .state_dict_adapter import DeepSeekV4StateDictAdapter |
| 42 | 39 | ||
| 43 | __all__ = [ | 40 | __all__ = [ |
| 44 | - "DeepSeekV4MTPDecoder", | ||
| 45 | - "DeepSeekV4MTPTransformerBlock", | ||
| 46 | "DeepSeekV4Model", | 41 | "DeepSeekV4Model", |
| 47 | "MTPLoss", | 42 | "MTPLoss", |
| 48 | "deepseek_v4_configs", | 43 | "deepseek_v4_configs", |
| @@ -475,11 +470,8 @@ def _build_mtp_layers( | |||
| 475 | n_main_layers: int, | 470 | n_main_layers: int, |
| 476 | num_mtp_layers: int, | 471 | num_mtp_layers: int, |
| 477 | rope: RoPE.Config, | 472 | rope: RoPE.Config, |
| 478 | -) -> list[DeepSeekV4MTPTransformerBlock.Config]: | 473 | +) -> list[MTPBlock.Config]: |
| 479 | """Build independent, non-compressed DSV4 MTP depths.""" | 474 | """Build independent, non-compressed DSV4 MTP depths.""" |
| 480 | - if num_mtp_layers < 0: | ||
| 481 | - raise ValueError(f"num_mtp_layers must be non-negative, got {num_mtp_layers}.") | ||
| 482 | - | ||
| 483 | mtp_layers = [] | 475 | mtp_layers = [] |
| 484 | for depth in range(num_mtp_layers): | 476 | for depth in range(num_mtp_layers): |
| 485 | layer_id = n_main_layers + depth | 477 | layer_id = n_main_layers + depth |
| @@ -509,21 +501,22 @@ def _build_mtp_layers( | |||
| 509 | 501 | ||
| 510 | hc_attn_pre = copy.deepcopy(inner_cfg.hc_attn_pre) | 502 | hc_attn_pre = copy.deepcopy(inner_cfg.hc_attn_pre) |
| 511 | projection = _build_mtp_projection(dim) | 503 | projection = _build_mtp_projection(dim) |
| 504 | + # Upstream builds the NPU configs via Config.build(). | ||
| 512 | mtp_layers.append( | 505 | mtp_layers.append( |
| 513 | - DeepSeekV4MTPTransformerBlock.Config( | 506 | + MTPBlock.Config( |
| 514 | - attention=attention, | 507 | + attention=attention, # pyrefly: ignore [bad-argument-type] |
| 515 | attention_norm=copy.deepcopy(inner_cfg.attention_norm), | 508 | attention_norm=copy.deepcopy(inner_cfg.attention_norm), |
| 516 | ffn_norm=copy.deepcopy(inner_cfg.ffn_norm), | 509 | ffn_norm=copy.deepcopy(inner_cfg.ffn_norm), |
| 517 | - moe=moe, | 510 | + moe=moe, # pyrefly: ignore [bad-argument-type] |
| 518 | enorm=copy.deepcopy(inner_cfg.attention_norm), | 511 | enorm=copy.deepcopy(inner_cfg.attention_norm), |
| 519 | hnorm=copy.deepcopy(inner_cfg.attention_norm), | 512 | hnorm=copy.deepcopy(inner_cfg.attention_norm), |
| 520 | e_proj=copy.deepcopy(projection), | 513 | e_proj=copy.deepcopy(projection), |
| 521 | h_proj=copy.deepcopy(projection), | 514 | h_proj=copy.deepcopy(projection), |
| 522 | mtp_norm=copy.deepcopy(inner_cfg.attention_norm), | 515 | mtp_norm=copy.deepcopy(inner_cfg.attention_norm), |
| 523 | - hc_attn_pre=hc_attn_pre, | 516 | + hc_attn_pre=hc_attn_pre, # pyrefly: ignore [bad-argument-type] |
| 524 | - hc_ffn_pre=copy.deepcopy(inner_cfg.hc_ffn_pre), | 517 | + hc_ffn_pre=copy.deepcopy(inner_cfg.hc_ffn_pre), # pyrefly: ignore [bad-argument-type] |
| 525 | - hc_post=copy.deepcopy(inner_cfg.hc_post), | 518 | + hc_post=copy.deepcopy(inner_cfg.hc_post), # pyrefly: ignore [bad-argument-type] |
| 526 | - hc_head=HcHead.Config( | 519 | + hc_head=HcHead.Config( # pyrefly: ignore [bad-argument-type] |
| 527 | hc_mult=hc_attn_pre.hc_mult, | 520 | hc_mult=hc_attn_pre.hc_mult, |
| 528 | dim=dim, | 521 | dim=dim, |
| 529 | norm_eps=hc_attn_pre.norm_eps, | 522 | norm_eps=hc_attn_pre.norm_eps, |
| @@ -583,6 +576,9 @@ def _make_v4_config( | |||
| 583 | ) -> DeepSeekV4Model.Config: | 576 | ) -> DeepSeekV4Model.Config: |
| 584 | """Build a DSV4 model config from the flavor constants.""" | 577 | """Build a DSV4 model config from the flavor constants.""" |
| 585 | 578 | ||
| 579 | + if num_mtp_layers < 0: | ||
| 580 | + raise ValueError(f"num_mtp_layers must be non-negative, got {num_mtp_layers}.") | ||
| 581 | + | ||
| 586 | rope = ComplexRoPE.Config( | 582 | rope = ComplexRoPE.Config( |
| 587 | dim=rope_head_dim, | 583 | dim=rope_head_dim, |
| 588 | max_context_length=max_seq_len, | 584 | max_context_length=max_seq_len, |
| @@ -3,25 +3,44 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 3 | # This source code is licensed under the BSD-style license found in the |
| 4 | # LICENSE file in the root directory of this source tree. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -from dataclasses import dataclass | 6 | +from collections.abc import Hashable |
| 7 | +from contextlib import nullcontext | ||
| 8 | +from dataclasses import dataclass, field, replace | ||
| 7 | from typing import TYPE_CHECKING, Any, cast | 9 | from typing import TYPE_CHECKING, Any, cast |
| 8 | 10 | ||
| 9 | import torch | 11 | import torch |
| 10 | from torch import nn | 12 | from torch import nn |
| 11 | -from torchtitan.config import TORCH_DTYPE_MAP, TrainingConfig | 13 | +from torchtitan.config import TORCH_DTYPE_MAP, TrainingConfig, derive |
| 12 | from torchtitan.config.parallelism import ParallelismConfig | 14 | from torchtitan.config.parallelism import ParallelismConfig |
| 13 | from torchtitan.distributed.parallelism_context import ParallelismContext | 15 | from torchtitan.distributed.parallelism_context import ParallelismContext |
| 14 | from torchtitan.models.common.decoder import Decoder, TransformerBlock | 16 | from torchtitan.models.common.decoder import Decoder, TransformerBlock |
| 17 | +from torchtitan.models.common.linear import Linear | ||
| 15 | from torchtitan.models.common.moe import MoE | 18 | from torchtitan.models.common.moe import MoE |
| 19 | +from torchtitan.models.deepseek_v3.mtp import roll_mtp_sequence | ||
| 16 | from torchtitan.models.utils import get_nparams_and_active_nparams | 20 | from torchtitan.models.utils import get_nparams_and_active_nparams |
| 21 | +from torchtitan.protocols.module import ModuleList | ||
| 22 | + | ||
| 23 | +from torchtitan_npu.models.common.linear import SharedLinear | ||
| 24 | +from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import ( | ||
| 25 | + AttentionMetadataMap, | ||
| 26 | +) | ||
| 17 | 27 | ||
| 18 | from .metadata import DeepSeekV4Metadata | 28 | from .metadata import DeepSeekV4Metadata |
| 19 | -from .mhc import HcPost, HcPre | 29 | +from .mhc import HcHead, HcPost, HcPre |
| 20 | -from .mtp import DeepSeekV4MTPDecoder, MTPBatch, prepare_mtp_batch | 30 | +from .mtp import MTPBatch, MTPModelOutput, _annotate_mtp_batch, _mtp_head_context, prepare_mtp_batch |
| 21 | 31 | ||
| 22 | if TYPE_CHECKING: | 32 | if TYPE_CHECKING: |
| 33 | + from torchtitan.models.deepseek_v4.mtp import MTPBlock | ||
| 34 | + | ||
| 35 | + from .attention import Attention | ||
| 23 | from .compressor import Indexer | 36 | from .compressor import Indexer |
| 24 | - from .mtp import DeepSeekV4MTPTransformerBlock | 37 | + |
| 38 | + | ||
| 39 | +def _require_attention_metadata(metadata: AttentionMetadataMap, key: Hashable) -> Any: | ||
| 40 | + entry = metadata.get(key) | ||
| 41 | + if entry is None: | ||
| 42 | + raise ValueError(f"no attention metadata was built for {key!r}") | ||
| 43 | + return entry | ||
| 25 | 44 | ||
| 26 | 45 | ||
| 27 | class DeepSeekV4TransformerBlock(TransformerBlock): | 46 | class DeepSeekV4TransformerBlock(TransformerBlock): |
| @@ -76,7 +95,7 @@ class DeepSeekV4TransformerBlock(TransformerBlock): | |||
| 76 | return x | 95 | return x |
| 77 | 96 | ||
| 78 | 97 | ||
| 79 | -class DeepSeekV4Model(DeepSeekV4MTPDecoder): | 98 | +class DeepSeekV4Model(Decoder): |
| 80 | @classmethod | 99 | @classmethod |
| 81 | def _register_optimizer_hooks(cls, optimizers, model_parts, parallelism_context): | 100 | def _register_optimizer_hooks(cls, optimizers, model_parts, parallelism_context): |
| 82 | from torchtitan.models.common.moe import register_moe_load_balancing_hook | 101 | from torchtitan.models.common.moe import register_moe_load_balancing_hook |
| @@ -106,7 +125,7 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 106 | apply_fsdp_to_mtp_decoder( | 125 | apply_fsdp_to_mtp_decoder( |
| 107 | # The helper requires the decoder/layers/MTP structure, shared by | 126 | # The helper requires the decoder/layers/MTP structure, shared by |
| 108 | # this implementation and the upstream DeepSeek V4 model. | 127 | # this implementation and the upstream DeepSeek V4 model. |
| 109 | - self, | 128 | + self, # pyrefly: ignore [bad-argument-type] |
| 110 | dp_mesh, | 129 | dp_mesh, |
| 111 | param_dtype=TORCH_DTYPE_MAP[training.mixed_precision_param], | 130 | param_dtype=TORCH_DTYPE_MAP[training.mixed_precision_param], |
| 112 | reduce_dtype=TORCH_DTYPE_MAP[training.mixed_precision_reduce], | 131 | reduce_dtype=TORCH_DTYPE_MAP[training.mixed_precision_reduce], |
| @@ -121,13 +140,26 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 121 | ) | 140 | ) |
| 122 | 141 | ||
| 123 | @dataclass(kw_only=True, slots=True) | 142 | @dataclass(kw_only=True, slots=True) |
| 124 | - class Config(DeepSeekV4MTPDecoder.Config): | 143 | + class Config(Decoder.Config): |
| 125 | vocab_size: int | 144 | vocab_size: int |
| 126 | compress_ratios: tuple[int, ...] | 145 | compress_ratios: tuple[int, ...] |
| 127 | n_layers: int | 146 | n_layers: int |
| 147 | + hc_mult: int = 4 | ||
| 148 | + hc_head: HcHead.Config | ||
| 149 | + mtp_layers: list["MTPBlock.Config"] = field(default_factory=list) | ||
| 150 | + mtp_isolate_gradients: bool = False | ||
| 128 | 151 | ||
| 129 | def update_from_config(self, *, config, **kwargs): | 152 | def update_from_config(self, *, config, **kwargs): |
| 130 | - DeepSeekV4MTPDecoder.Config.update_from_config(self, config=config, **kwargs) | 153 | + self.mtp_isolate_gradients = getattr(getattr(config, "loss", None), "mtp_isolate_gradients", False) |
| 154 | + # Apply runtime MoE/debug settings to auxiliary depths as well as main layers. | ||
| 155 | + num_main_layers = len(self.layers) | ||
| 156 | + self.layers.extend(self.mtp_layers or ()) | ||
| 157 | + try: | ||
| 158 | + Decoder.Config.update_from_config(self, config=config, **kwargs) | ||
| 159 | + finally: | ||
| 160 | + del self.layers[num_main_layers:] | ||
| 161 | + if self.mtp_layers and config.parallelism.pipeline_parallel_degree > 1: | ||
| 162 | + raise NotImplementedError("DeepSeek V4 MTP does not support pipeline parallelism yet.") | ||
| 131 | parallelism = config.parallelism | 163 | parallelism = config.parallelism |
| 132 | if parallelism.context_parallel_degree > 1: | 164 | if parallelism.context_parallel_degree > 1: |
| 133 | from torchtitan_npu.models.common.alignment import require_dataloader_alignment | 165 | from torchtitan_npu.models.common.alignment import require_dataloader_alignment |
| @@ -185,7 +217,7 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 185 | num_flops_per_token += 6 * attention.n_heads * (2 * attention.head_dim) * compressed_seq_len | 217 | num_flops_per_token += 6 * attention.n_heads * (2 * attention.head_dim) * compressed_seq_len |
| 186 | 218 | ||
| 187 | model_mtp_layers = deepseek_v4_model.mtp_layers | 219 | model_mtp_layers = deepseek_v4_model.mtp_layers |
| 188 | - if model_mtp_layers is not None: | 220 | + if model_mtp_layers: |
| 189 | lm_head = cast("nn.Module", deepseek_v4_model.lm_head) | 221 | lm_head = cast("nn.Module", deepseek_v4_model.lm_head) |
| 190 | num_flops_per_token += 6 * len(model_mtp_layers) * sum(param.numel() for param in lm_head.parameters()) | 222 | num_flops_per_token += 6 * len(model_mtp_layers) * sum(param.numel() for param in lm_head.parameters()) |
| 191 | num_flops_per_token += ( | 223 | num_flops_per_token += ( |
| @@ -194,14 +226,120 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 194 | * sum( | 226 | * sum( |
| 195 | param.numel() | 227 | param.numel() |
| 196 | for mtp_layer in model_mtp_layers | 228 | for mtp_layer in model_mtp_layers |
| 197 | - for param in cast("DeepSeekV4MTPTransformerBlock", mtp_layer).h_proj.parameters() | 229 | + for param in cast("MTPBlock", mtp_layer).h_proj.parameters() |
| 198 | ) | 230 | ) |
| 199 | ) | 231 | ) |
| 200 | 232 | ||
| 201 | return nparams, num_flops_per_token | 233 | return nparams, num_flops_per_token |
| 202 | 234 | ||
| 203 | def __init__(self, config: Config): | 235 | def __init__(self, config: Config): |
| 236 | + if config.mtp_isolate_gradients: | ||
| 237 | + if not config.mtp_layers or type(config.lm_head) is not Linear.Config: | ||
| 238 | + raise ValueError("MTP gradient isolation requires MTP layers and an unmodified Linear LM head.") | ||
| 239 | + config = derive(config, type(config), lm_head=derive(config.lm_head, SharedLinear.Config)) | ||
| 204 | super().__init__(config) | 240 | super().__init__(config) |
| 241 | + self.hc_mult = config.hc_mult | ||
| 242 | + self.hc_head = config.hc_head.build() | ||
| 243 | + self.mtp_layers = ModuleList(layer.build() for layer in config.mtp_layers) | ||
| 244 | + self.mtp_isolate_gradients = config.mtp_isolate_gradients | ||
| 245 | + | ||
| 246 | + def forward( # pyrefly: ignore [bad-override] | ||
| 247 | + self, | ||
| 248 | + tokens: torch.Tensor, | ||
| 249 | + positions: torch.Tensor | None = None, | ||
| 250 | + *, | ||
| 251 | + attention_metadata: AttentionMetadataMap, | ||
| 252 | + mtp_batch: MTPBatch | None = None, | ||
| 253 | + padding_mask: torch.Tensor | None = None, | ||
| 254 | + ) -> torch.Tensor | list[torch.Tensor]: | ||
| 255 | + if len(self.mtp_layers) > 0 and self.tok_embeddings is None: | ||
| 256 | + raise ValueError("DeepSeek V4 MTP forward requires token embeddings.") | ||
| 257 | + input_ids_T = tokens.detach().long() | ||
| 258 | + hidden = self.tok_embeddings(tokens) if self.tok_embeddings is not None else tokens | ||
| 259 | + hidden = hidden.unsqueeze(1).repeat(1, self.hc_mult, 1) | ||
| 260 | + for layer in self.layers.values(): | ||
| 261 | + hidden = layer( | ||
| 262 | + hidden, | ||
| 263 | + input_ids_T, | ||
| 264 | + _require_attention_metadata( | ||
| 265 | + attention_metadata, cast("Attention", layer.attention).attention_metadata_key | ||
| 266 | + ), | ||
| 267 | + positions, | ||
| 268 | + padding_mask=padding_mask, | ||
| 269 | + ) | ||
| 270 | + prev_hc_hidden = hidden | ||
| 271 | + main_hidden = self.hc_head(hidden) | ||
| 272 | + main_hidden = self.norm(main_hidden) if self.norm is not None else main_hidden | ||
| 273 | + | ||
| 274 | + if len(self.mtp_layers) == 0: | ||
| 275 | + if self._skip_lm_head or self.lm_head is None: | ||
| 276 | + return main_hidden | ||
| 277 | + return self.lm_head(main_hidden) | ||
| 278 | + | ||
| 279 | + outputs = [ | ||
| 280 | + main_hidden, | ||
| 281 | + *self.mtp_forward( | ||
| 282 | + prev_hc_hidden, | ||
| 283 | + tokens, | ||
| 284 | + positions, | ||
| 285 | + attention_metadata=attention_metadata, | ||
| 286 | + mtp_batch=mtp_batch, | ||
| 287 | + padding_mask=padding_mask, | ||
| 288 | + ), | ||
| 289 | + ] | ||
| 290 | + if not self._skip_lm_head and self.lm_head is not None: | ||
| 291 | + outputs[0] = self.lm_head(outputs[0]) | ||
| 292 | + with _mtp_head_context(self.lm_head, isolate_gradients=self.mtp_isolate_gradients): | ||
| 293 | + outputs[1:] = [self.lm_head(item) for item in outputs[1:]] | ||
| 294 | + return MTPModelOutput(outputs, mtp_labels=mtp_batch.labels if mtp_batch is not None else None) | ||
| 295 | + | ||
| 296 | + def mtp_forward( | ||
| 297 | + self, | ||
| 298 | + prev_hc_hidden: torch.Tensor, | ||
| 299 | + tokens: torch.Tensor, | ||
| 300 | + positions: torch.Tensor | None = None, | ||
| 301 | + *, | ||
| 302 | + attention_metadata: AttentionMetadataMap, | ||
| 303 | + mtp_batch: MTPBatch | None = None, | ||
| 304 | + padding_mask: torch.Tensor | None = None, | ||
| 305 | + ) -> list[torch.Tensor]: | ||
| 306 | + """Run auxiliary MTP depths, using globally prepared inputs under CP.""" | ||
| 307 | + if mtp_batch is not None: | ||
| 308 | + if mtp_batch.input_tokens.shape[-1] != len(self.mtp_layers): | ||
| 309 | + raise ValueError("Prepared MTP input depth does not match model layers.") | ||
| 310 | + _annotate_mtp_batch(mtp_batch) | ||
| 311 | + mtp_outputs = [] | ||
| 312 | + prev_hc_hidden = prev_hc_hidden.detach() if self.mtp_isolate_gradients else prev_hc_hidden | ||
| 313 | + for depth, mtp_block in enumerate(self.mtp_layers, 1): | ||
| 314 | + if mtp_batch is None: | ||
| 315 | + mtp_tokens, valid_mask = roll_mtp_sequence( | ||
| 316 | + tokens, | ||
| 317 | + shift=depth, | ||
| 318 | + fill_value=0, | ||
| 319 | + positions=positions, | ||
| 320 | + padding_mask=padding_mask, | ||
| 321 | + return_valid_mask=True, | ||
| 322 | + ) | ||
| 323 | + else: | ||
| 324 | + mtp_tokens = mtp_batch.input_tokens[..., depth - 1] | ||
| 325 | + valid_mask = mtp_batch.input_valid_mask[..., depth - 1] | ||
| 326 | + with torch.no_grad() if self.mtp_isolate_gradients else nullcontext(): | ||
| 327 | + mtp_embed = self.tok_embeddings(mtp_tokens) | ||
| 328 | + # MTPBlock calls the upstream V4 TransformerBlock.forward. Changes to | ||
| 329 | + # the NPU main-stack block above also need review for this path. | ||
| 330 | + prev_hc_hidden, prediction_hidden = mtp_block( | ||
MTP 现在走的是上游 ![]() ![]() | |||
| 331 | + mtp_embed, | ||
| 332 | + prev_hc_hidden, | ||
| 333 | + mtp_tokens.detach().long(), | ||
| 334 | + valid_mask, | ||
| 335 | + _require_attention_metadata( | ||
| 336 | + attention_metadata, cast("Attention", mtp_block.attention).attention_metadata_key | ||
| 337 | + ), | ||
| 338 | + positions, | ||
| 339 | + padding_mask=padding_mask, | ||
| 340 | + ) | ||
| 341 | + mtp_outputs.append(prediction_hidden) | ||
| 342 | + return mtp_outputs | ||
| 205 | 343 | ||
| 206 | def preprocess_inputs( | 344 | def preprocess_inputs( |
| 207 | self, | 345 | self, |
| @@ -228,10 +366,9 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 228 | the shard builds its balancer from the row and permutes the replicated row | 366 | the shard builds its balancer from the row and permutes the replicated row |
| 229 | before slicing, so no rank moves anything. The depths ride the same shard, | 367 | before slicing, so no rank moves anything. The depths ride the same shard, |
| 230 | handed the same row's positions, so the two agree row for row by | 368 | handed the same row's positions, so the two agree row for row by |
| 231 | - construction. Without context parallel or without MTP depths nothing changes. | 369 | + construction. With CP disabled, the prepared batch already matches the input row. |
| 232 | """ | 370 | """ |
| 233 | labels = input_dict["labels"] | 371 | labels = input_dict["labels"] |
| 234 | - cp_mesh = parallelism_context.get_mesh("cp") if parallelism_context.cp_enabled else None | ||
| 235 | positions = input_dict.get("positions") | 372 | positions = input_dict.get("positions") |
| 236 | padding_mask = input_dict.get("padding_mask") | 373 | padding_mask = input_dict.get("padding_mask") |
| 237 | mtp_batch = None | 374 | mtp_batch = None |
| @@ -239,16 +376,12 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 239 | # parallelism adds a second step that shards the prepared tensors, but | 376 | # parallelism adds a second step that shards the prepared tensors, but |
| 240 | # the non-CP path must retain the same padding/document-boundary | 377 | # the non-CP path must retain the same padding/document-boundary |
| 241 | # validity masks as well. | 378 | # validity masks as well. |
| 242 | - if self.mtp_layers is not None: | 379 | + if self.mtp_layers: |
| 243 | - mtp_kwargs = {} if padding_mask is None else {"padding_mask": padding_mask} | 380 | + mtp_batch = prepare_mtp_batch( |
| 244 | - mtp_batch = prepare_mtp_batch(input_dict["input"], labels, positions, len(self.mtp_layers), **mtp_kwargs) | 381 | + input_dict["input"], labels, positions, len(self.mtp_layers), padding_mask=padding_mask |
| 382 | + ) | ||
| 245 | 383 | ||
| 246 | - # ``MTPDecoder.preprocess_inputs`` returns the community tuple protocol | 384 | + inputs, labels, extra_kwargs = super().preprocess_inputs( |
| 247 | - # (main tokens, shifted tokens, ...). DSV4 owns a separate MTP block | ||
| 248 | - # and its global-row/CP preparation, so call the Decoder seam directly | ||
| 249 | - # and keep the model-facing input as one token tensor. | ||
| 250 | - inputs, labels, extra_kwargs = Decoder.preprocess_inputs( | ||
| 251 | - self, | ||
| 252 | input_dict, | 385 | input_dict, |
| 253 | parallelism_context=parallelism_context, | 386 | parallelism_context=parallelism_context, |
| 254 | parallelism=parallelism, | 387 | parallelism=parallelism, |
| @@ -260,18 +393,26 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder): | |||
| 260 | # With CP disabled the global row is already the model row. Under | 393 | # With CP disabled the global row is already the model row. Under |
| 261 | # CP, cut every MTP tensor with the exact decoder input layout so | 394 | # CP, cut every MTP tensor with the exact decoder input layout so |
| 262 | # shifted tokens stay aligned with the main stream. | 395 | # shifted tokens stay aligned with the main stream. |
| 263 | - if cp_mesh is None: | 396 | + if not parallelism_context.cp_enabled: |
| 264 | extra_kwargs["mtp_batch"] = mtp_batch | 397 | extra_kwargs["mtp_batch"] = mtp_batch |
| 265 | return inputs, labels, extra_kwargs | 398 | return inputs, labels, extra_kwargs |
| 266 | - # The layout the batch was sharded by, resolved exactly as the decoder resolves it: | ||
| 267 | - # an unset flag means "the layout this stack declares", and reading the raw config | ||
| 268 | - # value here would cut the depths contiguously while the inputs are permuted. | ||
| 269 | from torchtitan.models.common.decoder_sharding import decoder_input_sharding | 399 | from torchtitan.models.common.decoder_sharding import decoder_input_sharding |
| 270 | 400 | ||
| 401 | + from torchtitan_npu.patches.torchtitan.distributed.context_parallel import resolve_cp_load_balancer | ||
| 402 | + from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import cp_layout_of | ||
| 403 | + | ||
| 271 | mtp_inputs = {f"mtp_{index}": tensor for index, tensor in enumerate(mtp_batch)} | 404 | mtp_inputs = {f"mtp_{index}": tensor for index, tensor in enumerate(mtp_batch)} |
| 272 | if positions is not None: | 405 | if positions is not None: |
| 273 | mtp_inputs["positions"] = positions | 406 | mtp_inputs["positions"] = positions |
| 274 | sharding = decoder_input_sharding()["input"] | 407 | sharding = decoder_input_sharding()["input"] |
| 408 | + # The main metadata selects doc_chunk implicitly. Reuse its layout | ||
| 409 | + # without sending rank-local attention metadata through CP again. | ||
| 410 | + balancer_config = resolve_cp_load_balancer( | ||
| 411 | + parallelism.context_parallel_load_balancer, | ||
| 412 | + cp_layout_of(extra_kwargs.get("attention_metadata")), | ||
| 413 | + ) | ||
| 414 | + if balancer_config is not parallelism.context_parallel_load_balancer: | ||
| 415 | + parallelism = replace(parallelism, context_parallel_load_balancer=balancer_config) | ||
| 275 | sharded = self._cp_shard( | 416 | sharded = self._cp_shard( |
| 276 | mtp_inputs, | 417 | mtp_inputs, |
| 277 | input_shardings=dict.fromkeys(mtp_inputs, sharding), | 418 | input_shardings=dict.fromkeys(mtp_inputs, sharding), |
| @@ -3,48 +3,17 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 3 | # This source code is licensed under the BSD-style license found in the |
| 4 | # LICENSE file in the root directory of this source tree. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -from __future__ import annotations | ||
| 7 | - | ||
| 8 | -__all__ = [ | ||
| 9 | - "DeepSeekV4MTPDecoder", | ||
| 10 | - "DeepSeekV4MTPTransformerBlock", | ||
| 11 | - "MTPBatch", | ||
| 12 | - "MTPChunkedLossWrapper", | ||
| 13 | - "MTPLoss", | ||
| 14 | - "MTPModelOutput", | ||
| 15 | - "prepare_mtp_batch", | ||
| 16 | - "roll_mtp_sequence", | ||
| 17 | -] | ||
| 18 | - | ||
| 19 | from contextlib import nullcontext | 6 | from contextlib import nullcontext |
| 20 | from dataclasses import dataclass | 7 | from dataclasses import dataclass |
| 21 | from typing import Any, NamedTuple, cast | 8 | from typing import Any, NamedTuple, cast |
| 22 | 9 | ||
| 23 | import spmd_types as spmd | 10 | import spmd_types as spmd |
| 24 | import torch | 11 | import torch |
| 25 | -from torchtitan.components.loss import ( | 12 | +from torchtitan.components.loss import IGNORE_INDEX, BaseLoss, ChunkedLossWrapper |
| 26 | - IGNORE_INDEX, | 13 | +from torchtitan.models.deepseek_v3.mtp import MTPLoss as MTPLoss |
| 27 | - BaseLoss, | 14 | +from torchtitan.models.deepseek_v3.mtp import roll_mtp_sequence |
| 28 | - ChunkedLossWrapper, | ||
| 29 | -) | ||
| 30 | -from torchtitan.config import derive | ||
| 31 | -from torchtitan.models.common.decoder import Decoder, TransformerBlock | ||
| 32 | -from torchtitan.models.common.linear import Linear | ||
| 33 | -from torchtitan.models.common.moe import MoE # noqa: TC002 | ||
| 34 | -from torchtitan.models.common.nn_modules import RMSNorm # noqa: TC002 | ||
| 35 | -from torchtitan.models.deepseek_v3.mtp import ( | ||
| 36 | - MTPDecoder, | ||
| 37 | - MTPLoss, | ||
| 38 | - roll_mtp_sequence, | ||
| 39 | -) | ||
| 40 | -from torchtitan.protocols.module import ModuleList | ||
| 41 | 15 | ||
| 42 | from torchtitan_npu.models.common.linear import SharedLinear | 16 | from torchtitan_npu.models.common.linear import SharedLinear |
| 43 | -from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import ( # noqa: TC001 | ||
| 44 | - AttentionMetadataMap, | ||
| 45 | -) | ||
| 46 | - | ||
| 47 | -from .mhc import HcHead, HcPost, HcPre # noqa: TC001 | ||
| 48 | 17 | ||
| 49 | 18 | ||
| 50 | class MTPBatch(NamedTuple): | 19 | class MTPBatch(NamedTuple): |
| @@ -244,285 +213,3 @@ class MTPChunkedLossWrapper(ChunkedLossWrapper): | |||
| 244 | total_loss = total_loss + depth_loss | 213 | total_loss = total_loss + depth_loss |
| 245 | metrics = self._combine_chunk_metrics(metrics, depth_metrics) | 214 | metrics = self._combine_chunk_metrics(metrics, depth_metrics) |
| 246 | return total_loss, metrics | 215 | return total_loss, metrics |
| 247 | - | ||
| 248 | - | ||
| 249 | -class _MTPAttentionContext(NamedTuple): | ||
| 250 | - """What every DSV4 layer reads for its attention, main and MTP depths. | ||
| 251 | - | ||
| 252 | - The per-microbatch metadata map (upstream #4897) is built once for the whole | ||
| 253 | - stack -- main layers and MTP depths together -- and each layer reads the entry | ||
| 254 | - its own attention backend named. There is no single-object fallback: the V4 | ||
| 255 | - cores all build their own metadata, so a layer whose key is missing is a | ||
| 256 | - config that built none for a backend it runs, not a reason to hand it another | ||
| 257 | - geometry's grid. | ||
| 258 | - """ | ||
| 259 | - | ||
| 260 | - attention_metadata: AttentionMetadataMap | ||
| 261 | - positions: torch.Tensor | None | ||
| 262 | - | ||
| 263 | - def for_layer(self, layer: Any) -> Any: | ||
| 264 | - """The metadata one layer reads: its own map entry, keyed by its backend.""" | ||
| 265 | - key = layer.attention.attention_metadata_key | ||
| 266 | - metadata = self.attention_metadata.get(key) | ||
| 267 | - if metadata is None: | ||
| 268 | - raise ValueError(f"no attention metadata was built for {key!r}") | ||
| 269 | - return metadata | ||
| 270 | - | ||
| 271 | - | ||
| 272 | -class _MTPForwardState(NamedTuple): | ||
| 273 | - tok_embeddings: Any | ||
| 274 | - hc_hidden: torch.Tensor | ||
| 275 | - main_hidden: torch.Tensor | ||
| 276 | - | ||
| 277 | - | ||
| 278 | -class DeepSeekV4MTPTransformerBlock(TransformerBlock): | ||
| 279 | - """One DSV4 MTP depth that preserves the multi-stream mHC state.""" | ||
| 280 | - | ||
| 281 | - @dataclass(kw_only=True, slots=True) | ||
| 282 | - class Config(TransformerBlock.Config): | ||
| 283 | - moe: MoE.Config # pyrefly: ignore [bad-override] | ||
| 284 | - hc_attn_pre: HcPre.Config | ||
| 285 | - hc_ffn_pre: HcPre.Config | ||
| 286 | - hc_post: HcPost.Config | ||
| 287 | - enorm: RMSNorm.Config | ||
| 288 | - hnorm: RMSNorm.Config | ||
| 289 | - e_proj: Linear.Config | ||
| 290 | - h_proj: Linear.Config | ||
| 291 | - mtp_norm: RMSNorm.Config | ||
| 292 | - hc_head: HcHead.Config | ||
| 293 | - | ||
| 294 | - def __init__(self, config: Config): | ||
| 295 | - super().__init__() | ||
| 296 | - self.moe_enabled = True | ||
| 297 | - self.attention = config.attention.build() | ||
| 298 | - self.attention_norm = config.attention_norm.build() | ||
| 299 | - self.ffn_norm = config.ffn_norm.build() | ||
| 300 | - self.moe = config.moe.build() | ||
| 301 | - self.hc_attn_pre = config.hc_attn_pre.build() | ||
| 302 | - self.hc_ffn_pre = config.hc_ffn_pre.build() | ||
| 303 | - self.hc_post = config.hc_post.build() | ||
| 304 | - self.enorm = config.enorm.build() | ||
| 305 | - self.hnorm = config.hnorm.build() | ||
| 306 | - self.e_proj = config.e_proj.build() | ||
| 307 | - self.h_proj = config.h_proj.build() | ||
| 308 | - self.mtp_norm = config.mtp_norm.build() | ||
| 309 | - self.hc_head = config.hc_head.build() | ||
| 310 | - | ||
| 311 | - def forward( # pyrefly: ignore [bad-override] | ||
| 312 | - self, | ||
| 313 | - mtp_input_embed: torch.Tensor, | ||
| 314 | - prev_hc_hidden: torch.Tensor, | ||
| 315 | - mtp_input_ids: torch.Tensor, | ||
| 316 | - mtp_input_valid_mask: torch.Tensor, | ||
| 317 | - attention_context: _MTPAttentionContext, | ||
| 318 | - *, | ||
| 319 | - padding_mask: torch.Tensor | None = None, | ||
| 320 | - ) -> tuple[torch.Tensor, torch.Tensor]: | ||
| 321 | - if prev_hc_hidden.ndim != 3: | ||
| 322 | - raise ValueError( | ||
| 323 | - "DeepSeek-V4 MTP expects an mHC hidden state with shape " | ||
| 324 | - "[tokens, hc_mult, hidden], got " | ||
| 325 | - f"{tuple(prev_hc_hidden.shape)}." | ||
| 326 | - ) | ||
| 327 | - | ||
| 328 | - valid_mask = mtp_input_valid_mask.unsqueeze(-1).unsqueeze(-1).to(dtype=prev_hc_hidden.dtype) | ||
| 329 | - prev_hc_hidden = prev_hc_hidden * valid_mask | ||
| 330 | - | ||
| 331 | - hidden = self.e_proj(self.enorm(mtp_input_embed)).unsqueeze(1) | ||
| 332 | - hidden = hidden + self.h_proj(self.hnorm(prev_hc_hidden)) | ||
| 333 | - residual = hidden | ||
| 334 | - hidden, post, comb = self.hc_attn_pre(hidden) | ||
| 335 | - hidden = self.attention( | ||
| 336 | - self.attention_norm(hidden), | ||
| 337 | - attention_context.for_layer(self), | ||
| 338 | - attention_context.positions, | ||
| 339 | - ) | ||
| 340 | - hidden = self.hc_post(hidden, residual, post, comb) | ||
| 341 | - | ||
| 342 | - residual = hidden | ||
| 343 | - hidden, post, comb = self.hc_ffn_pre(hidden) | ||
| 344 | - mtp_padding_mask = ~mtp_input_valid_mask | ||
| 345 | - if padding_mask is not None: | ||
| 346 | - mtp_padding_mask = mtp_padding_mask | padding_mask | ||
| 347 | - hidden = self.moe( | ||
| 348 | - self.ffn_norm(hidden), | ||
| 349 | - input_ids_T=mtp_input_ids, | ||
| 350 | - padding_mask_T=mtp_padding_mask, | ||
| 351 | - ) | ||
| 352 | - next_hc_hidden = self.hc_post(hidden, residual, post, comb) | ||
| 353 | - | ||
| 354 | - prediction_hidden = self.hc_head(next_hc_hidden) | ||
| 355 | - prediction_hidden = self.mtp_norm(prediction_hidden) | ||
| 356 | - return next_hc_hidden, prediction_hidden | ||
| 357 | - | ||
| 358 | - | ||
| 359 | -class DeepSeekV4MTPDecoder(MTPDecoder): | ||
| 360 | - """DeepSeek-V4 decoder with optional multi-token prediction layers.""" | ||
| 361 | - | ||
| 362 | - @dataclass(kw_only=True, slots=True) | ||
| 363 | - class Config(MTPDecoder.Config): | ||
| 364 | - hc_mult: int = 4 | ||
| 365 | - hc_head: HcHead.Config | ||
| 366 | - mtp_isolate_gradients: bool = False | ||
| 367 | - | ||
| 368 | - def update_from_config(self, *, config, **kwargs) -> None: | ||
| 369 | - self.mtp_isolate_gradients = getattr(getattr(config, "loss", None), "mtp_isolate_gradients", False) | ||
| 370 | - if not self.mtp_layers: | ||
| 371 | - Decoder.Config.update_from_config( | ||
| 372 | - self, | ||
| 373 | - config=config, | ||
| 374 | - **kwargs, | ||
| 375 | - ) | ||
| 376 | - return | ||
| 377 | - | ||
| 378 | - num_main_layers = len(self.layers) | ||
| 379 | - self.layers.extend(self.mtp_layers) | ||
| 380 | - try: | ||
| 381 | - Decoder.Config.update_from_config( | ||
| 382 | - self, | ||
| 383 | - config=config, | ||
| 384 | - **kwargs, | ||
| 385 | - ) | ||
| 386 | - finally: | ||
| 387 | - del self.layers[num_main_layers:] | ||
| 388 | - | ||
| 389 | - if config.parallelism.pipeline_parallel_degree > 1: | ||
| 390 | - raise NotImplementedError("MTP does not support pipeline parallelism yet.") | ||
| 391 | - | ||
| 392 | - def __init__(self, config: Config): | ||
| 393 | - if config.mtp_isolate_gradients: | ||
| 394 | - if not config.mtp_layers or type(config.lm_head) is not Linear.Config: | ||
| 395 | - raise ValueError("MTP gradient isolation requires MTP layers and an unmodified Linear LM head.") | ||
| 396 | - config = derive(config, type(config), lm_head=derive(config.lm_head, SharedLinear.Config)) | ||
| 397 | - # MTPDecoder builds the community MTP block type. DSV4 owns a | ||
| 398 | - # different block while retaining the same decoder-level contract. | ||
| 399 | - Decoder.__init__(self, config) | ||
| 400 | - self.mtp_isolate_gradients = config.mtp_isolate_gradients | ||
| 401 | - self.hc_mult = config.hc_mult | ||
| 402 | - self.hc_head = config.hc_head.build() | ||
| 403 | - | ||
| 404 | - if not config.mtp_layers: | ||
| 405 | - self.mtp_layers = None | ||
| 406 | - return | ||
| 407 | - | ||
| 408 | - self.mtp_layers = ModuleList() | ||
| 409 | - for layer_config in config.mtp_layers: | ||
| 410 | - self.mtp_layers.append(layer_config.build()) | ||
| 411 | - | ||
| 412 | - def forward( # pyrefly: ignore [bad-override] | ||
| 413 | - self, | ||
| 414 | - tokens: torch.Tensor, | ||
| 415 | - positions: torch.Tensor | None = None, | ||
| 416 | - *, | ||
| 417 | - attention_metadata: AttentionMetadataMap, | ||
| 418 | - mtp_batch: MTPBatch | None = None, | ||
| 419 | - padding_mask: torch.Tensor | None = None, | ||
| 420 | - ) -> torch.Tensor | list[torch.Tensor]: | ||
| 421 | - """The metadata map is the pinned argument's replacement, not a renaming of it. | ||
| 422 | - | ||
| 423 | - The pinned ``MTPDecoder.forward`` takes one mask object for every layer; this decoder | ||
| 424 | - takes the decoder's map and hands each layer the entry of its own geometry, so the | ||
| 425 | - parameter is keyword-only and the pinned name would be a lie. | ||
| 426 | - """ | ||
| 427 | - attention_context = _MTPAttentionContext(attention_metadata, positions) | ||
| 428 | - state = self._forward_main(tokens, attention_context, padding_mask=padding_mask) | ||
| 429 | - | ||
| 430 | - if self.mtp_layers is None: | ||
| 431 | - if self._skip_lm_head or self.lm_head is None: | ||
| 432 | - return state.main_hidden | ||
| 433 | - return self.lm_head(state.main_hidden) | ||
| 434 | - | ||
| 435 | - if state.tok_embeddings is None: | ||
| 436 | - raise ValueError("DeepSeek-V4 MTP forward requires token embeddings.") | ||
| 437 | - | ||
| 438 | - outputs = [ | ||
| 439 | - state.main_hidden, | ||
| 440 | - *self._forward_mtp_layers( | ||
| 441 | - tokens, | ||
| 442 | - state, | ||
| 443 | - attention_context, | ||
| 444 | - mtp_batch, | ||
| 445 | - padding_mask=padding_mask, | ||
| 446 | - ), | ||
| 447 | - ] | ||
| 448 | - if not self._skip_lm_head and self.lm_head is not None: | ||
| 449 | - outputs[0] = self.lm_head(outputs[0]) | ||
| 450 | - with _mtp_head_context(self.lm_head, isolate_gradients=self.mtp_isolate_gradients): | ||
| 451 | - outputs[1:] = [self.lm_head(item) for item in outputs[1:]] | ||
| 452 | - return MTPModelOutput( | ||
| 453 | - outputs, | ||
| 454 | - mtp_labels=mtp_batch.labels if mtp_batch is not None else None, | ||
| 455 | - ) | ||
| 456 | - | ||
| 457 | - def _forward_main( | ||
| 458 | - self, | ||
| 459 | - tokens: torch.Tensor, | ||
| 460 | - attention_context: _MTPAttentionContext, | ||
| 461 | - *, | ||
| 462 | - padding_mask: torch.Tensor | None = None, | ||
| 463 | - ) -> _MTPForwardState: | ||
| 464 | - tok_embeddings = self.tok_embeddings | ||
| 465 | - input_ids = tokens.detach().long() | ||
| 466 | - hidden = tok_embeddings(tokens) if tok_embeddings is not None else tokens | ||
| 467 | - hidden = hidden.unsqueeze(1).repeat(1, self.hc_mult, 1) | ||
| 468 | - | ||
| 469 | - for layer in self.layers.values(): | ||
| 470 | - hidden = layer( | ||
| 471 | - hidden, | ||
| 472 | - input_ids, | ||
| 473 | - attention_context.for_layer(layer), | ||
| 474 | - attention_context.positions, | ||
| 475 | - padding_mask=padding_mask, | ||
| 476 | - ) | ||
| 477 | - | ||
| 478 | - main_hidden = self.hc_head(hidden) | ||
| 479 | - main_hidden = self.norm(main_hidden) if self.norm is not None else main_hidden | ||
| 480 | - return _MTPForwardState(tok_embeddings, hidden, main_hidden) | ||
| 481 | - | ||
| 482 | - def _forward_mtp_layers( | ||
| 483 | - self, | ||
| 484 | - tokens: torch.Tensor, | ||
| 485 | - state: _MTPForwardState, | ||
| 486 | - attention_context: _MTPAttentionContext, | ||
| 487 | - mtp_batch: MTPBatch | None, | ||
| 488 | - *, | ||
| 489 | - padding_mask: torch.Tensor | None = None, | ||
| 490 | - ) -> list[torch.Tensor]: | ||
| 491 | - if self.mtp_layers is None: | ||
| 492 | - return [] | ||
| 493 | - if mtp_batch is not None: | ||
| 494 | - if mtp_batch.input_tokens.shape[-1] != len(self.mtp_layers): | ||
| 495 | - raise ValueError( | ||
| 496 | - "Prepared MTP input depth does not match model layers: " | ||
| 497 | - f"{mtp_batch.input_tokens.shape[-1]} inputs for " | ||
| 498 | - f"{len(self.mtp_layers)} layers." | ||
| 499 | - ) | ||
| 500 | - _annotate_mtp_batch(mtp_batch) | ||
| 501 | - | ||
| 502 | - mtp_outputs = [] | ||
| 503 | - prev_hc_hidden = state.hc_hidden.detach() if self.mtp_isolate_gradients else state.hc_hidden | ||
| 504 | - for depth, layer in enumerate(self.mtp_layers, 1): | ||
| 505 | - if mtp_batch is None: | ||
| 506 | - mtp_tokens, valid_mask = roll_mtp_sequence( | ||
| 507 | - tokens, | ||
| 508 | - shift=depth, | ||
| 509 | - fill_value=0, | ||
| 510 | - positions=attention_context.positions, | ||
| 511 | - padding_mask=padding_mask, | ||
| 512 | - return_valid_mask=True, | ||
| 513 | - ) | ||
| 514 | - else: | ||
| 515 | - mtp_tokens = mtp_batch.input_tokens[..., depth - 1] | ||
| 516 | - valid_mask = mtp_batch.input_valid_mask[..., depth - 1] | ||
| 517 | - with torch.no_grad() if self.mtp_isolate_gradients else nullcontext(): | ||
| 518 | - mtp_embed = state.tok_embeddings(mtp_tokens) | ||
| 519 | - prev_hc_hidden, prediction_hidden = layer( | ||
| 520 | - mtp_embed, | ||
| 521 | - prev_hc_hidden, | ||
| 522 | - mtp_tokens.detach().long(), | ||
| 523 | - valid_mask, | ||
| 524 | - attention_context, | ||
| 525 | - padding_mask=padding_mask, | ||
| 526 | - ) | ||
| 527 | - mtp_outputs.append(prediction_hidden) | ||
| 528 | - return mtp_outputs | ||
| @@ -14,7 +14,21 @@ from torch.distributed.tensor.experimental._context_parallel._load_balancer impo | |||
| 14 | from torchtitan.distributed.context_parallel import ContextParallelLoadBalancer | 14 | from torchtitan.distributed.context_parallel import ContextParallelLoadBalancer |
| 15 | from torchtitan.distributed.spmd_types import spmd_mesh_group | 15 | from torchtitan.distributed.spmd_types import spmd_mesh_group |
| 16 | 16 | ||
| 17 | -from torchtitan_npu.models.common.restore import doc_chunk_permutation, document_starts | 17 | +from torchtitan_npu.models.common.restore import DOC_CHUNK_LAYOUT, doc_chunk_permutation, document_starts |
| 18 | + | ||
| 19 | + | ||
| 20 | +def resolve_cp_load_balancer( | ||
| 21 | + config: ContextParallelLoadBalancer.Config | None, | ||
| 22 | + metadata_layout: str | None, | ||
| 23 | +) -> ContextParallelLoadBalancer.Config | None: | ||
| 24 | + """Resolve the typed CP balancer for the layout required by attention metadata.""" | ||
| 25 | + if metadata_layout != DOC_CHUNK_LAYOUT: | ||
| 26 | + return config | ||
| 27 | + if config is None: | ||
| 28 | + return DocChunkCPLoadBalancer.Config() | ||
| 29 | + if not isinstance(config, DocChunkCPLoadBalancer.Config): | ||
| 30 | + raise ValueError("Document-chunk attention metadata requires DocChunkCPLoadBalancer.Config.") | ||
| 31 | + return config | ||
| 18 | 32 | ||
| 19 | 33 | ||
| 20 | class DocChunkLoadBalancer(_LoadBalancer): | 34 | class DocChunkLoadBalancer(_LoadBalancer): |
| @@ -136,16 +136,15 @@ def _cp_shard( | |||
| 136 | ) -> dict[str, Any]: | 136 | ) -> dict[str, Any]: |
| 137 | """Prepare rank-local backend metadata with the native typed CP shard.""" | 137 | """Prepare rank-local backend metadata with the native typed CP shard.""" |
| 138 | from torchtitan_npu.models.common.restore import DOC_CHUNK_LAYOUT | 138 | from torchtitan_npu.models.common.restore import DOC_CHUNK_LAYOUT |
| 139 | - from torchtitan_npu.patches.torchtitan.distributed.context_parallel import DocChunkCPLoadBalancer | 139 | + from torchtitan_npu.patches.torchtitan.distributed.context_parallel import ( |
| 140 | + DocChunkCPLoadBalancer, | ||
| 141 | + resolve_cp_load_balancer, | ||
| 142 | + ) | ||
| 140 | from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import cp_layout_of | 143 | from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import cp_layout_of |
| 141 | 144 | ||
| 142 | metadata = input_dict.get("attention_metadata") | 145 | metadata = input_dict.get("attention_metadata") |
| 143 | positions = input_dict.get("positions") | 146 | positions = input_dict.get("positions") |
| 144 | - balancer_config = parallelism.context_parallel_load_balancer | 147 | + balancer_config = resolve_cp_load_balancer(parallelism.context_parallel_load_balancer, cp_layout_of(metadata)) |
| 145 | - if cp_layout_of(metadata) == DOC_CHUNK_LAYOUT: | ||
| 146 | - if balancer_config is not None and not isinstance(balancer_config, DocChunkCPLoadBalancer.Config): | ||
| 147 | - raise ValueError("Document-chunk attention metadata requires DocChunkCPLoadBalancer.Config.") | ||
| 148 | - balancer_config = DocChunkCPLoadBalancer.Config() | ||
| 149 | layout = ( | 148 | layout = ( |
| 150 | DOC_CHUNK_LAYOUT | 149 | DOC_CHUNK_LAYOUT |
| 151 | if isinstance(balancer_config, DocChunkCPLoadBalancer.Config) | 150 | if isinstance(balancer_config, DocChunkCPLoadBalancer.Config) |


请将 PR 描述中的上游提交从
dc3985ad更正为ebdfc8c2,与当前依赖声明保持一致。