Closed
refactor: 清理 DeepSeek-V4 模型适配与重复代码 #1257
hanboyouAdd on 23 days agoClosed at 19 days ago
refactor: 清理 DeepSeek-V4 模型适配与重复代码 #1257
Closed
hanboyouAdd on 23 days agoClosed at 19 days ago
Total: 45 files changed+485-2206
@@ -34,6 +34,8 @@
34 ".compile.dynamo_config"34 ".compile.dynamo_config"
35 ],35 ],
36 "torchtitan_npu/patches/torchtitan/__init__.py": [36 "torchtitan_npu/patches/torchtitan/__init__.py": [
37+ ".models.base",
38+ ".distributed.fsdp",
37 ".components.metrics",39 ".components.metrics",
38 ".components.optimizer",40 ".components.optimizer",
39 ".observability",41 ".observability",
@@ -285,13 +285,13 @@ System: Ascend 950,图模式
285 285 
1Fire4
1Fire41Fire422 days ago

跑一下43层、8卡16专家的训练对比下精度和性能

likedislike
286| 模型 | NPU 数 | 量化 | GBS | 序列长度 | FSDP | TP | PP | CP | EP | 单卡吞吐 (tokens/s) | step time | BF16 MFU |286| 模型 | NPU 数 | 量化 | GBS | 序列长度 | FSDP | TP | PP | CP | EP | 单卡吞吐 (tokens/s) | step time | BF16 MFU |
287| :--- | ---: | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |287| :--- | ---: | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
288-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 64 | MXFP8 | 512 | 4k | 64 | 1 | 1 | 1 | 64 | 2126 | 15.42 s | / |288+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 64 | MXFP8 | 512 | 4k | 64 | 1 | 1 | 1 | 64 | 2126 | 15.42 s | / |
289-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 64 | MXFP8 | 64 | 64k | 8 | 1 | 1 | 8 | 64 | 1501.6 | 43.64 s | / |289+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 64 | MXFP8 | 64 | 64k | 8 | 1 | 1 | 8 | 64 | 1501.6 | 43.64 s | / |
290-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 128 | MXFP8 | 8 | 1M | 1 | 1 | 1 | 128 | 128 | 1325 | 49.46 s | / |290+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 128 | MXFP8 | 8 | 1M | 1 | 1 | 1 | 128 | 128 | 1325 | 49.46 s | / |
291-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 64 | BF16 | 512 | 4k | 64 | 1 | 1 | 1 | 64 | 1603 | 20.44 s | 28.81% |291+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 64 | BF16 | 512 | 4k | 64 | 1 | 1 | 1 | 64 | 1603 | 20.44 s | 28.81% |
292-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 64 | BF16 | 64 | 64k | 8 | 1 | 1 | 8 | 64 | 1421 | 46.12 s | 32.87% |292+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 64 | BF16 | 64 | 64k | 8 | 1 | 1 | 8 | 64 | 1421 | 46.12 s | 32.87% |
293-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 64 | QAT | 512 | 4k | 64 | 1 | 1 | 1 | 64 | 1576 | 20.79 s | / |293+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 64 | QAT | 512 | 4k | 64 | 1 | 1 | 1 | 64 | 1576 | 20.79 s | / |
294-| [DeepSeek-V4-Flash](torchtitan_npu/models/deepseek_v4/config_registry.py) | 64 | QAT | 64 | 64k | 8 | 1 | 1 | 8 | 64 | 1532 | 42.78 s | / |294+| [DeepSeek-V4-Flash](torchtitan_npu_recipes/models/deepseek_v4.py) | 64 | QAT | 64 | 64k | 8 | 1 | 1 | 8 | 64 | 1532 | 42.78 s | / |
295 295 
296 296 
297# 免责声明297# 免责声明
@@ -18,7 +18,7 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式
18 18 
19### 配置入口19### 配置入口
20 20 
21-`torchtitan_npu_recipes/graph_trainer/deepseek_v4.py` 保存图训练组合,均复用 `torchtitan_npu_recipes.models.deepseek_v4` 中的对应 eager 配置,经 `torchtitan_npu/models/deepseek_v4/graph_trainer.py` 的 `to_graph_trainer_config` 包装为 `GraphTrainer.Config`:21+`torchtitan_npu_recipes/graph_trainer/deepseek_v4.py` 保存图训练组合,均复用 `torchtitan_npu_recipes.models.deepseek_v4` 中的对应 eager 配置。recipe 先通过上游 `derive(base, Trainer.Config)` 投影到基础 trainer schema,再调用上游 `to_graph_trainer_config` 构造 `GraphTrainer.Config`。投影移除顶层 NPU 扩展字段,保留嵌套组件配置:
22 22 
23| 配置名 | 对应 eager 配置 |23| 配置名 | 对应 eager 配置 |
24| --- | --- |24| --- | --- |
@@ -28,7 +28,7 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式
28| `graph_trainer_deepseek_v4_pro` | `deepseek_v4_pro` |28| `graph_trainer_deepseek_v4_pro` | `deepseek_v4_pro` |
29| `graph_trainer_deepseek_v4_pro_61layers_32experts` | `deepseek_v4_pro_61layers_32experts` |29| `graph_trainer_deepseek_v4_pro_61layers_32experts` | `deepseek_v4_pro_61layers_32experts` |
30 30 
31-编译配置统一为 `mode="aot_fx_trace"`、`memory_policy="full"`、`disable_passes=["cudagraph_pass"]`。模型通过 `_graph_trainer_model_registry` 包装为 `GraphTrainerDeepSeekV4Model.Config`,并行化函数指向 `parallelize_graph_trainer_deepseek_v4`。31+编译配置统一为 `mode="aot_fx_trace"`、`memory_policy="full"`、`disable_passes=["cudagraph_pass"]`。上游转换器将模型配置转换为 `GraphTrainerDeepSeekV4Model.Config`,并行化函数指向 `parallelize_graph_trainer_deepseek_v4`。
32 32 
33### 模型变体33### 模型变体
34 34 
@@ -26,7 +26,7 @@ A5 使用 `CONFIG=deepseek_v4_flash_lora bash examples/deepseek_v4/deepseek_v4_f
26```python26```python
27from torchtitan.config.transform import apply_transforms27from torchtitan.config.transform import apply_transforms
28 28 
29-from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash29+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash
30from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform30from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform
31from torchtitan_npu.models.deepseek_v4.peft import DeepSeekV4PEFTCheckpointManager31from torchtitan_npu.models.deepseek_v4.peft import DeepSeekV4PEFTCheckpointManager
32 32 
@@ -1,6 +1,6 @@
1# DeepSeek-V4 TND 适配1# DeepSeek-V4 TND 适配
2 2 
3-DeepSeek-V4(DSV4)在模型层使用文档打包(varlen)的 `[B, S, ...]` 接口;压缩 KV 在非 CP 下是 `[B, S//r, D]` 整行,CP 下是本地 chunk(内核边界 all-gather 成整行),仅在进入 AscendC 融合内核时转换为 TND。本文说明当前实现、启用方式和已知边界。3+本文保留 DeepSeek-V4(DSV4)旧版整层注意力的文档几何、carry 与 TND 设计说明。该路径的 backend 转换入口和专属测试已删除。当前维护的 recipe 使用原生注意力配置与 checkpoint 布局,通过组件 override 选择 NPU 实现;eager 路径要求 TP=CP=PP=1,模型接口为折叠后的 token 流。下文旧版 `[B, S, ...]` 接口及 CP 流程不代表当前 recipe 的支持范围。
4 4 
5## 启用方式5## 启用方式
6 6 
@@ -189,7 +189,7 @@ python -m tests.integration_tests.run_tests /tmp/dsv4-grain-sft-results \
189| --- | --- |189| --- | --- |
190| `positions` | 必须提供 `[B, S]`,且每条序列从 0 连续递增 |190| `positions` | 必须提供 `[B, S]`,且每条序列从 0 连续递增 |
191| Padding | varlen 流必须覆盖本 rank 的全部 `B * S` 个 token,metadata 不表达 padding token |191| Padding | varlen 流必须覆盖本 rank 的全部 `B * S` 个 token,metadata 不表达 padding token |
192-| Context Parallel | 支持(AscendC 融合路径,CLI 指定 `NGPU=2 bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh --parallelism.context-parallel-degree 2 --parallelism.spmd-backend spmd_types --parallelism.context-parallel-load-balancer doc_chunk --dataloader.per_doc_alignment 256`);**静态 doc-chunk 布局**:`cp_shard` 在切之前按 `doc_chunk_permutation` 重排整行(零通信),所以输入(token / positions / labels / MTP 深度)一次就是「每篇文档的第 r 个 chunk」,本层 KV 侧再用 `cp.restore` 恢复到 slab,KV/压缩 KV 整行;布局与还原在 `models/common/restore.py`(`doc_chunk_permutation` / `chunk_plan` / `to_slab`),两栈共用;ratio-4 carry 仍在 `models/common/carry_exchange.py` 的 `CarryExchange`(压缩器本身 CP-agnostic) |192+| Context Parallel | 当前维护的 eager recipe 不支持 CP>1,模型配置在构建前拒绝;本文的 doc-chunk 与 carry 流程仅说明旧版设计 |
193| Tensor Parallel | DSA 路径固定 TP=1(indexer score 对 head 维求和),TP 方案待 CP 之后另行设计 |193| Tensor Parallel | DSA 路径固定 TP=1(indexer score 对 head 维求和),TP 方案待 CP 之后另行设计 |
194| 空压缩流 | doc-packing 场景要求每条序列至少产生一个完整压缩块;融合路径在 metadata 边界对 `ratio > 1` 且无完整块直接报错(AscendC CSA/HCA 不接受空 `cmp_kv`) |194| 空压缩流 | doc-packing 场景要求每条序列至少产生一个完整压缩块;融合路径在 metadata 边界对 `ratio > 1` 且无完整块直接报错(AscendC CSA/HCA 不接受空 `cmp_kv`) |
195| 运行环境 | 需要 `torch_npu`、CANN、HCCL、Ascend NPU,以及匹配的 `cann_ops_transformer` |195| 运行环境 | 需要 `torch_npu`、CANN、HCCL、Ascend NPU,以及匹配的 `cann_ops_transformer` |
@@ -10,6 +10,12 @@ torchtitan-npu 通过 TorchAO-NPU 为 DeepSeek-V4 和 DeepSeek-V4.1 提供 MXFP8
10 10 
11配置默认关闭量化训练,DeepSeek-V4/DeepSeek-V4.1 的 A5 示例脚本会显式启用量化。11配置默认关闭量化训练,DeepSeek-V4/DeepSeek-V4.1 的 A5 示例脚本会显式启用量化。
12 12 
13+## DeepSeek-V4 FSDP 参数精度
14+ 
15+DeepSeek-V4 的混合精度 FSDP 保留 mHC、compressor APE、attention sink 和训练 router 的参数精度,覆盖主干与 MTP 层。共享策略使用参数自身 dtype 与 `param_dtype` 中较宽的类型;FP32 权重不会先经过 BF16 舍入,BF16 权重也不会被无条件提升为 FP32。`reduce_dtype` 保持训练配置指定的值。
16+ 
17+TorchTitan 0.4.0 通过包导入时安装的共享策略读取模块运行期声明,模型继承上游 FSDP/MTP 流程。该适配回移上游 [#5774](https://github.com/pytorch/torchtitan/pull/5774) 的精度策略机制,保留既有 Config 类型,不新增配置参数,也不改变 GraphTrainer SimpleFSDP、checkpoint 导出或 RL 权重传输。具体加载边界见[架构说明](../architecture.md#两阶段时序语义)。
18+ 
13## 当前支持的数据格式19## 当前支持的数据格式
14 20 
15当前实现中的量化数据和 scale 表示如下。不同量化路径分别使用低精度计算或 fake quant,并通过对应的反向实现传递梯度。21当前实现中的量化数据和 scale 表示如下。不同量化路径分别使用低精度计算或 fake quant,并通过对应的反向实现传递梯度。
@@ -138,7 +138,7 @@ DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造
138| `deepseek_v4/__init__.py` | 根据模型规格构造非压缩、mHC-aware 的 MTP blocks |138| `deepseek_v4/__init__.py` | 根据模型规格构造非压缩、mHC-aware 的 MTP blocks |
139| `deepseek_v4/model.py` | 保留主干多流 state,并组织主预测和 MTP 预测 |139| `deepseek_v4/model.py` | 保留主干多流 state,并组织主预测和 MTP 预测 |
140| `deepseek_v4/mtp.py` | 实现 DeepSeek-V4 mHC MTP block、CP batch 和 chunk loss |140| `deepseek_v4/mtp.py` | 实现 DeepSeek-V4 mHC MTP block、CP batch 和 chunk loss |
141-| `deepseek_v4/config_registry.py` | 默认 recipe 构造 MTP 模型并配置 MTP chunk loss |141+| `torchtitan_npu_recipes/models/deepseek_v4.py` | 默认 recipe 构造 MTP 模型并配置 MTP chunk loss |
142| `deepseek_v4/parallelize.py` | 让 MTP blocks 复用现有 DSV4 并行流程 |142| `deepseek_v4/parallelize.py` | 让 MTP blocks 复用现有 DSV4 并行流程 |
143| `deepseek_v4/sharding.py` | 增加 MTP fusion、mHC head 和有效掩码布局 |143| `deepseek_v4/sharding.py` | 增加 MTP fusion、mHC head 和有效掩码布局 |
144| `deepseek_v4/state_dict_adapter.py` | 转换本地 `mtp_layers` 与 HF `mtp.<depth>` 参数 |144| `deepseek_v4/state_dict_adapter.py` | 转换本地 `mtp_layers` 与 HF `mtp.<depth>` 参数 |
@@ -6,7 +6,7 @@
6from torchtitan.components.checkpointer import CheckpointManager6from torchtitan.components.checkpointer import CheckpointManager
7 7 
8from torchtitan_npu.config import CompileConfig, ModelCompileConfig8from torchtitan_npu.config import CompileConfig, ModelCompileConfig
9-from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel9+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_debugmodel
10 10 
11 11 
12def deepseek_v4_checkpoint():12def deepseek_v4_checkpoint():
@@ -7,7 +7,7 @@
7 7 
8Override-parity tests (``test_hc_*_override_matches_eager``) compare the8Override-parity tests (``test_hc_*_override_matches_eager``) compare the
9``torchtitan_npu.override.deepseek_v4.mhc`` Triton modules against their eager9``torchtitan_npu.override.deepseek_v4.mhc`` Triton modules against their eager
10-``torchtitan_npu.models.deepseek_v4.mhc`` counterparts for forward output and10+``torchtitan.models.deepseek_v4.mhc`` counterparts for forward output and
11backward gradients.11backward gradients.
12 12 
13Compile-safety tests (``test_mhc_*_compiled_backward``) verify that each13Compile-safety tests (``test_mhc_*_compiled_backward``) verify that each
@@ -29,9 +29,9 @@ with error 507035 (vector core exception).
29 29 
30import pytest30import pytest
31import torch31import torch
32+from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
32 33 
33from tests.conftest import assert_tensor_finite, stable_randn34from tests.conftest import assert_tensor_finite, stable_randn
34-from torchtitan_npu.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
35from torchtitan_npu.ops.triton.mhc.post_bmm1 import mhc_post_bmm1_op35from torchtitan_npu.ops.triton.mhc.post_bmm1 import mhc_post_bmm1_op
36from torchtitan_npu.ops.triton.mhc.post_bmm2 import mhc_post_bmm2_op36from torchtitan_npu.ops.triton.mhc.post_bmm2 import mhc_post_bmm2_op
37from torchtitan_npu.ops.triton.mhc.pre_bmm import mhc_pre_bmm_op37from torchtitan_npu.ops.triton.mhc.pre_bmm import mhc_pre_bmm_op
@@ -6,19 +6,25 @@
6"""Native FSDP precision retains model and MTP weights before computation."""6"""Native FSDP precision retains model and MTP weights before computation."""
7 7 
8import copy8import copy
9+from types import SimpleNamespace
9 10 
10import pytest11import pytest
11import torch12import torch
12import torch.distributed as dist13import torch.distributed as dist
14+import torchtitan.distributed.fsdp as fsdp
13from torch import nn15from torch import nn
14from torch.distributed.device_mesh import init_device_mesh16from torch.distributed.device_mesh import init_device_mesh
17+from torchtitan.config import TrainingConfig
18+from torchtitan.config.parallelism import ParallelismConfig
19+from torchtitan.models.base.module import Module
15from torchtitan.models.common.linear import Linear20from torchtitan.models.common.linear import Linear
21+from torchtitan.models.deepseek_v3.mtp import MTPDecoder, apply_fsdp_to_mtp_decoder
16from torchtitan.models.deepseek_v4.mhc import HcPre22from torchtitan.models.deepseek_v4.mhc import HcPre
17 23 
18-from torchtitan_npu.models.common.fsdp import apply_fsdp_to_mtp_decoder, make_param_dtype_override_fn24+from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4Model
19 25 
20 26 
21-class _ProjectionBlock(nn.Module):27+class _ProjectionBlock(Module):
22 """Use actual V4 mixing and Linear modules in the decoder sharding layout."""28 """Use actual V4 mixing and Linear modules in the decoder sharding layout."""
23 29 
24 def __init__(self):30 def __init__(self):
@@ -31,8 +37,8 @@ class _ProjectionBlock(nn.Module):
31 return self.feed_forward(reduced), post, comb37 return self.feed_forward(reduced), post, comb
32 38 
33 39 
34-class _MTPDecoderLayout(nn.Module):40+class _MTPDecoderLayout(Module):
35- """The layer/MTP containers consumed by the production sharding bridge."""41+ """Small layer/MTP composition consumed by the upstream FSDP entry points."""
36 42 
37 def __init__(self):43 def __init__(self):
38 super().__init__()44 super().__init__()
@@ -55,7 +61,8 @@ def cpu_mesh(tmp_path):
55 dist.destroy_process_group()61 dist.destroy_process_group()
56 62 
57 63 
58-def test_native_callback_preserves_fp32_model_and_mtp_weights_and_gradients(cpu_mesh):64+@pytest.mark.parametrize("entrypoint", ("mtp-helper", "mtp-model", "v4-model", "explicit-callback"))
65+def test_upstream_fsdp_preserves_declared_model_and_mtp_weights_and_gradients(cpu_mesh, entrypoint):
59 with torch.random.fork_rng(devices=[]):66 with torch.random.fork_rng(devices=[]):
60 model = _MTPDecoderLayout()67 model = _MTPDecoderLayout()
61 with torch.no_grad():68 with torch.no_grad():
@@ -66,19 +73,53 @@ def test_native_callback_preserves_fp32_model_and_mtp_weights_and_gradients(cpu_
66 masters = {name: parameter.detach().clone() for name, parameter in model.named_parameters()}73 masters = {name: parameter.detach().clone() for name, parameter in model.named_parameters()}
67 for block in (reference.layers["0"], reference.mtp_layers[0]):74 for block in (reference.layers["0"], reference.mtp_layers[0]):
68 block.feed_forward.to(dtype=torch.bfloat16)75 block.feed_forward.to(dtype=torch.bfloat16)
69- overrides = {name: torch.float32 for name in masters if ".hc_attn_pre." in name}76+ overrides = (
70- callback = make_param_dtype_override_fn(model, overrides)77+ {}
78+ if entrypoint == "explicit-callback"
79+ else {name: torch.float32 for name in masters if ".hc_attn_pre." in name}
80+ )
81+ if entrypoint == "explicit-callback":
82+ reference.bfloat16()
71 original_layers = tuple(model.layers)83 original_layers = tuple(model.layers)
72 84 
73- apply_fsdp_to_mtp_decoder(85+ if entrypoint == "explicit-callback":
74- model,86+ alias = str(len(model.layers))
75- cpu_mesh,87+ model.layers[alias] = model.mtp_layers[0]
76- param_dtype=torch.bfloat16,88+ try:
77- reduce_dtype=torch.float32,89+ fsdp.apply_fsdp_to_decoder(
78- pp_enabled=False,90+ model,
79- reshard_after_forward_policy="never",91+ cpu_mesh,
80- param_dtype_override_fn=callback,92+ param_dtype=torch.bfloat16,
81- )93+ reduce_dtype=torch.float32,
94+ pp_enabled=False,
95+ reshard_after_forward_policy="never",
96+ param_dtype_override_fn=lambda _parameter: None,
97+ )
98+ finally:
99+ del model.layers[alias]
100+ elif entrypoint == "mtp-helper":
101+ apply_fsdp_to_mtp_decoder(
102+ model,
103+ cpu_mesh,
104+ param_dtype=torch.bfloat16,
105+ reduce_dtype=torch.float32,
106+ pp_enabled=False,
107+ reshard_after_forward_policy="never",
108+ )
109+ else:
110+ context = SimpleNamespace(
111+ get_activated_mesh=lambda _axes: cpu_mesh,
112+ ep_enabled=False,
113+ pp_enabled=False,
114+ ep=1,
115+ )
116+ apply_fsdp = MTPDecoder._apply_fsdp if entrypoint == "mtp-model" else DeepSeekV4Model._apply_fsdp
117+ apply_fsdp(
118+ model,
119+ parallelism_context=context,
120+ training=TrainingConfig(mixed_precision_param="bfloat16", mixed_precision_reduce="float32"),
121+ parallelism=ParallelismConfig(fsdp_reshard_after_forward="never"),
122+ )
82 123 
83 assert tuple(model.layers) == original_layers124 assert tuple(model.layers) == original_layers
84 observed = {}125 observed = {}
@@ -51,11 +51,10 @@ def _build_model_config(num_experts=NUM_EXPERTS, num_layers=N_LAYERS, num_mtp_la
51 51 
52 52 
53def _lora_model_config(*, num_experts=2, num_layers=1, targets=None):53def _lora_model_config(*, num_experts=2, num_layers=1, targets=None):
54- from torchtitan_npu.models.deepseek_v4.backend import with_npu_attention_backend
55 from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform54 from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform
56 55 
57 transform = deepseek_v4_lora_transform(rank=8, alpha=16)56 transform = deepseek_v4_lora_transform(rank=8, alpha=16)
58 if targets is not None:57 if targets is not None:
59 transform.target_modules = targets58 transform.target_modules = targets
60- config = with_npu_attention_backend(_build_model_config(num_experts=num_experts, num_layers=num_layers))59+ config = _build_model_config(num_experts=num_experts, num_layers=num_layers)
61 return transform.transform(config)60 return transform.transform(config)
@@ -1,77 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-# SPDX-License-Identifier: BSD-3-Clause
3- 
4-import pytest
5-import torch
6-from torchtitan.config.parallelism import ParallelismConfig
7-from torchtitan.models.deepseek_v4 import build_model_config
8-from torchtitan.models.deepseek_v4.attention import DeepSeekV4Attention
9-from torchtitan.models.deepseek_v4.state_dict_adapter import DeepSeekV4StateDictAdapter as NativeStateDictAdapter
10- 
11-from torchtitan_npu.models.deepseek_v4.attention import NPUAttention
12-from torchtitan_npu.models.deepseek_v4.backend import (
13- NPUBackendDeepSeekV4Model,
14- to_npu_attention_config,
15- with_npu_attention_backend,
16-)
17- 
18- 
19-def test_npu_backend_selection_preserves_native_source_and_adapts_main_and_mtp():
20- native = build_model_config(
21- "debugmodel", seq_len=128, n_mtp_layers=1, parallelism=ParallelismConfig(), indexer_loss_coeff=0
22- )
23- native_attention = native.layers[0].attention
24- backend = with_npu_attention_backend(native)
25- 
26- assert type(native_attention) is DeepSeekV4Attention.Config
27- assert native.layers[0].attention is native_attention
28- assert native_attention.compress_ratio == 0
29- assert native_attention.rope.split == 0
30- assert isinstance(backend, NPUBackendDeepSeekV4Model.Config)
31- assert all(isinstance(layer.attention, NPUAttention.Config) for layer in (*backend.layers, *backend.mtp_layers))
32- assert backend.layers[0].attention.compress_ratio == 1
33- assert backend.layers[0].attention.rope.split == native_attention.head_dim - native_attention.rope_head_dim
34- assert backend.layers[3].attention.compressor is not None
35- assert backend.layers[3].attention.compressor.compress_ratio == 128
36- assert backend.layers[2].attention.lightning_indexer is not None
37- assert backend.layers[0].attention.lightning_indexer is None
38- 
39- 
40-def test_npu_backend_attention_keeps_projection_storage_and_selects_bare_sink():
41- config = build_model_config("debugmodel", seq_len=128, parallelism=ParallelismConfig(), indexer_loss_coeff=0)
42- native_config = config.layers[0].attention
43- backend_config = to_npu_attention_config(native_config)
44- with torch.device("meta"):
45- native = native_config.build()
46- backend = backend_config.build()
47- 
48- assert native.wo_a.weight.shape == backend.wo_a.weight.shape
49- assert native.attn_sink.weight.shape == (native_config.n_heads, 1)
50- assert backend.attn_sink.shape == (native_config.n_heads,)
51- assert "attn_sink.weight" in native.state_dict()
52- assert "attn_sink" in backend.state_dict()
53- 
54- 
55-def test_npu_backend_selects_matching_hf_checkpoint_names_and_sink_rank():
56- native = build_model_config("debugmodel", seq_len=128, parallelism=ParallelismConfig(), indexer_loss_coeff=0)
57- backend = with_npu_attention_backend(native)
58- sink = torch.arange(native.layers[0].attention.n_heads, dtype=torch.float32)
59- ape = torch.arange(4, dtype=torch.float32)
60- hf_state = {"layers.0.attn.attn_sink": sink, "layers.3.attn.compressor.ape": ape}
61- native_state = NativeStateDictAdapter(native, None).from_hf(hf_state)
62- backend_adapter = NPUBackendDeepSeekV4Model.state_dict_adapter_cls(backend, None)
63- backend_state = backend_adapter.from_hf(hf_state)
64- 
65- assert torch.equal(native_state["layers.0.attention.attn_sink.weight"], sink[:, None])
66- assert torch.equal(backend_state["layers.0.attention.attn_sink"], sink)
67- assert torch.equal(native_state["layers.3.attention.compressor_128.ape"], ape)
68- assert torch.equal(backend_state["layers.3.attention.compressor.ape"], ape)
69- round_trip = backend_adapter.to_hf(backend_state)
70- assert set(round_trip) == set(hf_state)
71- assert all(torch.equal(round_trip[name], value) for name, value in hf_state.items())
72- 
73- 
74-def test_npu_backend_rejects_untranslated_indexer_objective():
75- config = build_model_config("debugmodel", seq_len=128, parallelism=ParallelismConfig())
76- with pytest.raises(ValueError, match="indexer_loss_coeff=0"):
77- to_npu_attention_config(config.layers[2].attention)
@@ -5,6 +5,7 @@
5 5 
6from dataclasses import replace6from dataclasses import replace
7 7 
8+import pytest
8import torch9import torch
9from torchtitan.components.data import (10from torchtitan.components.data import (
10 ConcatThenSplitPackingConfig,11 ConcatThenSplitPackingConfig,
@@ -18,6 +19,17 @@ from torchtitan_npu.models.common.alignment import AlignedTextProcessor
18from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_debugmodel19from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_debugmodel
19 20 
20 21 
22+def test_native_model_rejects_cp_even_with_aligned_documents():
23+ config = deepseek_v4_debugmodel()
24+ config.parallelism.context_parallel_degree = 2
25+ config.dataloader.dataset.dataset.processor.per_doc_alignment = 256
26+ 
27+ with torch.device("meta"):
28+ model = config.model.build()
29+ with pytest.raises(NotImplementedError, match="TP=CP=PP=1"):
30+ model.parallelize(parallelism=config.parallelism)
31+ 
32+ 
21def test_debugmodel_uses_the_documented_per_layer_compression_ratios():33def test_debugmodel_uses_the_documented_per_layer_compression_ratios():
22 from torchtitan_npu.models.deepseek_v4 import model_registry34 from torchtitan_npu.models.deepseek_v4 import model_registry
23 35 
@@ -29,14 +29,12 @@ def _cpu_grouped_mm(self, *, input_RI, weight_EOI, offsets_E):
29 )29 )
30 30 
31 31 
32-@pytest.mark.parametrize("kind", ["dense", "batched", "grouped"], ids=["dense", "per-head", "routed"])32+@pytest.mark.parametrize("kind", ["dense", "grouped"], ids=["dense", "routed"])
33@pytest.mark.parametrize("replicated", [False, True], ids=["unsharded", "replicated"])33@pytest.mark.parametrize("replicated", [False, True], ids=["unsharded", "replicated"])
34def test_standard_lora_projection_output_and_gradients_match_independent_formula(kind, replicated, monkeypatch):34def test_standard_lora_projection_output_and_gradients_match_independent_formula(kind, replicated, monkeypatch):
35 config = _lora_model_config()35 config = _lora_model_config()
36 if kind == "dense":36 if kind == "dense":
37 projection = config.layers[0].attention.wq_a37 projection = config.layers[0].attention.wq_a
38- elif kind == "batched":
39- projection = config.layers[0].attention.wo_a
40 else:38 else:
41 projection = config.layers[0].feed_forward.routed_experts.w1339 projection = config.layers[0].feed_forward.routed_experts.w13
42 monkeypatch.setattr(GroupedLinear, "_grouped_mm", _cpu_grouped_mm)40 monkeypatch.setattr(GroupedLinear, "_grouped_mm", _cpu_grouped_mm)
@@ -49,8 +47,7 @@ def test_standard_lora_projection_output_and_gradients_match_independent_formula
49 module.init_states(buffer_device=torch.device("cpu"))47 module.init_states(buffer_device=torch.device("cpu"))
50 with torch.no_grad():48 with torch.no_grad():
51 module.lora_b.weight.normal_(std=0.1)49 module.lora_b.weight.normal_(std=0.1)
52- shape = (5, projection.n_heads, projection.in_features) if kind == "batched" else (5, projection.in_features)50+ inputs = torch.randn(5, projection.in_features, requires_grad=True)
53- inputs = torch.randn(shape, requires_grad=True)
54 a, b = module.lora_a.weight, module.lora_b.weight51 a, b = module.lora_a.weight, module.lora_b.weight
55 if kind == "grouped":52 if kind == "grouped":
56 offsets = torch.tensor([2, 5], dtype=torch.int32)53 offsets = torch.tensor([2, 5], dtype=torch.int32)
@@ -59,13 +56,6 @@ def test_standard_lora_projection_output_and_gradients_match_independent_formula
59 base = torch.einsum("ti,tsoi->tso", inputs, module.weight[experts])56 base = torch.einsum("ti,tsoi->tso", inputs, module.weight[experts])
60 hidden = torch.einsum("ti,tri->tr", inputs, a[experts])57 hidden = torch.einsum("ti,tri->tr", inputs, a[experts])
61 expected = base + 2 * torch.einsum("tr,tsor->tso", hidden, b[experts])58 expected = base + 2 * torch.einsum("tr,tsor->tso", hidden, b[experts])
62- elif kind == "batched":
63- actual = module(inputs)
64- base = torch.einsum("thi,hoi->tho", inputs, module.weight.view(projection.n_heads, projection.out_features, -1))
65- hidden = torch.einsum("thi,ri->thr", inputs, a)
66- expected = base + 2 * torch.einsum(
67- "thr,hor->tho", hidden, b.view(projection.n_heads, projection.out_features, -1)
68- )
69 else:59 else:
70 actual = module(inputs)60 actual = module(inputs)
71 expected = F.linear(inputs, module.weight) + 2 * (inputs @ a.T @ b.T)61 expected = F.linear(inputs, module.weight) + 2 * (inputs @ a.T @ b.T)
@@ -18,8 +18,9 @@ import copy
18 18 
19import pytest19import pytest
20import torch20import torch
21+from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
21 22 
22-from torchtitan_npu.models.deepseek_v4.mhc import HcHead, HcPost, HcPre23+import torchtitan_npu # noqa: F401 -- activate the upstream Sinkhorn patch
atomgit-bot
atomgit-botatomgit-bot23 days ago

🟡 Medium Priority

变更点:tests/unit_tests/models/deepseek_v4/test_mhc.py:21-23 先执行 from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre(把上游类对象绑定到模块全局),再执行 import torchtitan_npu # noqa: F401 -- activate the upstream Sinkhorn patch。

受影响契约:本文件注释明确表示该 import torchtitan_npu 的目的是"激活上游 Sinkhorn 补丁"。如果补丁(torchtitan_npu/patches/torchtitan/models/deepseek_v4/...)是通过把补丁类/函数重新赋值到 torchtitan.models.deepseek_v4.mhc 模块属性上实现的(本仓库 patches 目录下大量使用这种 monkeypatch 形式),那么 line 21 已经绑定的是旧类,line 23 的补丁只会修改模块属性,模块全局名不会更新。

失效模式:测试实际跑的是未打补丁的 Sinkhorn 实现,却因为结果与自身独立参考实现一致而通过(或者与期望的补丁后 epsilon 行为不一致而偶发失败),即"测试静默地测错对象",给出虚假的覆盖信心。只有当补丁是原地修改类方法(in-place monkeypatch)且 tests/conftest.py 未提前导入 torchtitan_npu 时才不触发。

修复方向:把 import torchtitan_npu 移到所有 torchtitan.models... 导入之前(或改为在激活补丁后再以 import torchtitan.models.deepseek_v4.mhc as mhc 属性方式取类)。

建议:将 import torchtitan_npu(激活最多补丁的导入)提到 from torchtitan.models.deepseek_v4.mhc import ... 之前,确保 eager 参考实现使用的是打过 Sinkhorn 补丁的类;或改用模块属性访问以避免导入期绑定。

likedislike
Incorrect?
23 24 
24 25 
25def _set_hc_pre_parameters(module):26def _set_hc_pre_parameters(module):
@@ -3,28 +3,42 @@
3# This source code is licensed under the BSD-style license found in the3# 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-"""V4 FP32 parameter families passed to native FSDP precision callbacks.6+"""V4 parameter declarations consumed by the shared FSDP precision policy.
7 7 
8The expected families below come from the released checkpoint's dtype audit8The expected families below come from the released checkpoint's dtype audit
9-and the deliberate FP32 training-router policy, independently of the selector.9+and the deliberate FP32 training-router policy, independently of the declarations.
10The native V4 layout stores HCA APE under ``compressor_128`` and attention sinks10The native V4 layout stores HCA APE under ``compressor_128`` and attention sinks
11inside ``Linear.weight``; both must retain the same checkpoint precision.11inside ``Linear.weight``; both must retain the same checkpoint precision.
12"""12"""
13 13 
14import fnmatch14import fnmatch
15+from dataclasses import dataclass
15 16 
16import pytest17import pytest
17import torch18import torch
19+import torchtitan.distributed.fsdp as fsdp
20+from torch import nn
18from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper21from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
19-from torchtitan.config import TrainingConfig22+from torchtitan.config import derive
23+from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router
20 24 
21from tests.unit_tests.models.mtp_test_utils import SEQ_LEN, VOCAB_SIZE, build_cpu_model25from tests.unit_tests.models.mtp_test_utils import SEQ_LEN, VOCAB_SIZE, build_cpu_model
22-from torchtitan_npu.models.common.fsdp import make_param_dtype_override_fn
23from torchtitan_npu.models.deepseek_v4 import _make_v4_config26from torchtitan_npu.models.deepseek_v4 import _make_v4_config
24-from torchtitan_npu.models.deepseek_v4.parallelize import _dsv4_param_dtypes
25 27 
26 28 
27-def _build_policy_model():29+class _RouterWithAdapter(DeepSeekV4Router):
30+ """Router owner containing a foreign adapter before model construction ends."""
31+ 
32+ @dataclass(kw_only=True, slots=True)
33+ class Config(DeepSeekV4Router.Config):
34+ pass
35+ 
36+ def __init__(self, config):
37+ super().__init__(config)
38+ self.adapter = nn.Linear(config.gate.in_features, config.num_experts, bias=True)
39+ 
40+ 
41+def _build_policy_model(*, router_adapter=False):
28 """Construct main HCA/CSA blocks and a dense MTP block through the factory."""42 """Construct main HCA/CSA blocks and a dense MTP block through the factory."""
29 config = _make_v4_config(43 config = _make_v4_config(
30 dim=32,44 dim=32,
@@ -58,6 +72,9 @@ def _build_policy_model():
58 original_seq_len=65536,72 original_seq_len=65536,
59 num_mtp_layers=1,73 num_mtp_layers=1,
60 )74 )
75+ if router_adapter:
76+ for layer in (*config.layers, *config.mtp_layers):
77+ layer.feed_forward.router = derive(layer.feed_forward.router, _RouterWithAdapter.Config)
61 with torch.random.fork_rng(devices=[]):78 with torch.random.fork_rng(devices=[]):
62 return build_cpu_model(config)79 return build_cpu_model(config)
63 80 
@@ -100,23 +117,45 @@ HF_F32 = (
100HF_F32_BUFFERS = ("layers.*.ffn.gate.bias", "mtp.*.ffn.gate.bias")117HF_F32_BUFFERS = ("layers.*.ffn.gate.bias", "mtp.*.ffn.gate.bias")
101 118 
102 119 
103-def test_native_v4_fp32_parameter_families_are_selected_exactly():120+def test_v4_declares_the_expected_fp32_parameter_families():
104 model = _build_policy_model()121 model = _build_policy_model()
122+ patterns = FP32_PARAMETERS
105 names = tuple(name for name, _ in model.named_parameters())123 names = tuple(name for name, _ in model.named_parameters())
106- unused = [pattern for pattern in FP32_PARAMETERS if not any(fnmatch.fnmatchcase(name, pattern) for name in names)]124+ unused = [pattern for pattern in patterns if not any(fnmatch.fnmatchcase(name, pattern) for name in names)]
107 assert not unused, f"Expected FP32 families absent from the model: {unused}"125 assert not unused, f"Expected FP32 families absent from the model: {unused}"
108- expected = {name for name in names if any(fnmatch.fnmatchcase(name, pattern) for pattern in FP32_PARAMETERS)}126+ expected = {name for name in names if any(fnmatch.fnmatchcase(name, pattern) for pattern in patterns)}
109 127 
110- dtypes = _dsv4_param_dtypes(model, TrainingConfig())128+ declared = dict(model.named_preserve_dtype_params())
111 129 
112- assert set(dtypes) == expected130+ assert set(declared) == expected
113- assert set(dtypes.values()) == {torch.float32}131+ assert {parameter.dtype for parameter in declared.values()} == {torch.float32}
114- assert "layers.0.attention.compressor_128.ape" in dtypes132+ assert "layers.0.attention.compressor_128.ape" in declared
115- assert "layers.2.attention.compressor.ape" in dtypes133+ assert "layers.2.attention.compressor.ape" in declared
116- assert "layers.2.attention.indexer.compressor.ape" in dtypes134+ assert "layers.2.attention.indexer.compressor.ape" in declared
117- assert "mtp_layers.0.attention.attn_sink.weight" in dtypes135+ assert "mtp_layers.0.attention.attn_sink.weight" in declared
118 for name in ("tok_embeddings.weight", "lm_head.weight", "norm.weight", "layers.0.attention.wq_a.weight"):136 for name in ("tok_embeddings.weight", "lm_head.weight", "norm.weight", "layers.0.attention.wq_a.weight"):
119- assert name in names and name not in dtypes137+ assert name in names and name not in declared
138+ 
139+ 
140+def test_model_declares_foreign_router_adapter_parameters_before_fsdp():
141+ model = _build_policy_model(router_adapter=True)
142+ declared = dict(model.named_preserve_dtype_params())
143+ callback = fsdp.mixed_precision_policy(
144+ model, param_dtype=torch.bfloat16, reduce_dtype=torch.float32
145+ ).param_dtype_override_fn
146+ assert callback is not None
147+ 
148+ for prefix, layer in (
149+ *((f"layers.{index}", layer) for index, layer in model.layers.items()),
150+ *((f"mtp_layers.{index}", layer) for index, layer in enumerate(model.mtp_layers)),
151+ ):
152+ adapter = layer.feed_forward.router.adapter
153+ assert type(adapter) is nn.Linear
154+ for suffix in ("weight", "bias"):
155+ parameter = getattr(adapter, suffix)
156+ assert declared[f"{prefix}.feed_forward.router.adapter.{suffix}"] is parameter
157+ assert callback(parameter) is torch.float32
158+ assert callback(layer.feed_forward.routed_experts.w13.weight) is None
120 159 
121 160 
122def test_every_f32_tensor_of_the_release_is_covered():161def test_every_f32_tensor_of_the_release_is_covered():
@@ -130,20 +169,36 @@ def test_every_f32_tensor_of_the_release_is_covered():
130 169 
131 170 
132@pytest.mark.parametrize("reduce_dtype", ("float32", "bfloat16"))171@pytest.mark.parametrize("reduce_dtype", ("float32", "bfloat16"))
133-def test_native_callback_only_changes_selected_parameter_compute_dtype(reduce_dtype):172+@pytest.mark.parametrize("master_dtype", (torch.float32, torch.bfloat16), ids=("fp32-masters", "bf16-masters"))
173+def test_shared_policy_only_changes_declared_parameter_compute_dtype(reduce_dtype, master_dtype):
134 model = _build_policy_model()174 model = _build_policy_model()
135- training = TrainingConfig(mixed_precision_param="bfloat16", mixed_precision_reduce=reduce_dtype)175+ if master_dtype is torch.bfloat16:
136- dtypes = _dsv4_param_dtypes(model, training)176+ model.bfloat16()
137- callback = make_param_dtype_override_fn(model, dtypes)177+ policy = fsdp.mixed_precision_policy(
178+ model,
179+ param_dtype=torch.bfloat16,
180+ reduce_dtype=getattr(torch, reduce_dtype),
181+ cast_forward_inputs=False,
182+ )
183+ 
184+ assert policy.param_dtype is torch.bfloat16
185+ assert policy.reduce_dtype is getattr(torch, reduce_dtype)
186+ assert not policy.cast_forward_inputs
187+ callback = policy.param_dtype_override_fn
188+ assert callback is not None
138 189 
139 for name, parameter in model.named_parameters():190 for name, parameter in model.named_parameters():
140- expected = torch.float32 if any(fnmatch.fnmatchcase(name, pattern) for pattern in FP32_PARAMETERS) else None191+ expected = (
192+ torch.promote_types(master_dtype, torch.bfloat16)
193+ if any(fnmatch.fnmatchcase(name, pattern) for pattern in FP32_PARAMETERS)
194+ else None
195+ )
141 assert callback(parameter) is expected, name196 assert callback(parameter) is expected, name
142 197 
143 198 
144@pytest.mark.parametrize("scope", ("main-attention", "main-block", "mtp-block"))199@pytest.mark.parametrize("scope", ("main-attention", "main-block", "mtp-block"))
145-def test_native_dtype_selection_survives_checkpoint_wrapping(scope):200+def test_declared_dtype_selection_survives_checkpoint_wrapping(scope):
146- plain_dtypes = _dsv4_param_dtypes(_build_policy_model(), TrainingConfig())201+ plain_names = set(dict(_build_policy_model().named_preserve_dtype_params()))
147 model = _build_policy_model()202 model = _build_policy_model()
148 if scope == "main-attention":203 if scope == "main-attention":
149 model.layers["0"].attention = checkpoint_wrapper(model.layers["0"].attention)204 model.layers["0"].attention = checkpoint_wrapper(model.layers["0"].attention)
@@ -152,30 +207,38 @@ def test_native_dtype_selection_survives_checkpoint_wrapping(scope):
152 else:207 else:
153 model.mtp_layers[0] = checkpoint_wrapper(model.mtp_layers[0])208 model.mtp_layers[0] = checkpoint_wrapper(model.mtp_layers[0])
154 209 
155- dtypes = _dsv4_param_dtypes(model, TrainingConfig())210+ declared = dict(model.named_preserve_dtype_params())
156- assert any("_checkpoint_wrapped_module" in name for name in dtypes)211+ assert any("_checkpoint_wrapped_module" in name for name in declared)
157 canonical = {212 canonical = {
158- ".".join(part for part in name.split(".") if part != "_checkpoint_wrapped_module"): dtype213+ ".".join(part for part in name.split(".") if part != "_checkpoint_wrapped_module") for name in declared
159- for name, dtype in dtypes.items()
160 }214 }
161- assert canonical == plain_dtypes215+ assert canonical == plain_names
162- callback = make_param_dtype_override_fn(model, dtypes)216+ callback = fsdp.mixed_precision_policy(
217+ model, param_dtype=torch.bfloat16, reduce_dtype=torch.float32
218+ ).param_dtype_override_fn
219+ assert callback is not None
163 for name, parameter in model.named_parameters():220 for name, parameter in model.named_parameters():
164- assert callback(parameter) is dtypes.get(name), name221+ expected = torch.float32 if name in declared else None
222+ assert callback(parameter) is expected, name
165 223 
166 224 
167-def test_native_callback_preserves_policy_through_temporary_mtp_layer_aliases():225+def test_shared_policy_preserves_parameters_through_temporary_mtp_layer_aliases():
168 model = _build_policy_model()226 model = _build_policy_model()
169 original_layers = tuple(model.layers)227 original_layers = tuple(model.layers)
170- dtypes = _dsv4_param_dtypes(model, TrainingConfig())228+ declared = {id(parameter) for _, parameter in model.named_preserve_dtype_params()}
171- callback = make_param_dtype_override_fn(model, dtypes)229+ callback = fsdp.mixed_precision_policy(
230+ model, param_dtype=torch.bfloat16, reduce_dtype=torch.float32
231+ ).param_dtype_override_fn
232+ assert callback is not None
172 key = str(len(model.layers))233 key = str(len(model.layers))
173 model.layers[key] = model.mtp_layers[0]234 model.layers[key] = model.mtp_layers[0]
174 try:235 try:
175 aliased_parameters = dict(model.named_parameters(remove_duplicate=False))236 aliased_parameters = dict(model.named_parameters(remove_duplicate=False))
237+ assert {id(parameter) for _, parameter in model.named_preserve_dtype_params()} == declared
176 for suffix, parameter in model.mtp_layers[0].named_parameters():238 for suffix, parameter in model.mtp_layers[0].named_parameters():
177 assert aliased_parameters[f"layers.{key}.{suffix}"] is parameter239 assert aliased_parameters[f"layers.{key}.{suffix}"] is parameter
178- assert callback(parameter) is dtypes.get(f"mtp_layers.0.{suffix}"), suffix240+ expected = torch.float32 if id(parameter) in declared else None
241+ assert callback(parameter) is expected, suffix
179 finally:242 finally:
180 del model.layers[key]243 del model.layers[key]
181 assert tuple(model.layers) == original_layers244 assert tuple(model.layers) == original_layers
@@ -1,360 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-#
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.
5- 
6-"""CPU contract of DeepSeek-V4's backend-owned metadata seam.
7- 
8-The sparse-attention core's own config builds what it consumes (upstream #4897): the
9-reference tier the packed contract, the fused AscendC tier that contract plus this
10-geometry's kernel records. The decoder builds one entry per backend geometry for the
11-whole microbatch, and the fused entry's own ``prepare_cp_metadata`` re-derives this
12-rank's copy (upstream #4617). The test keeps the contract's two ends -- per-geometry
13-entries and the rank-local rebuild -- and drops the per-field detail.
14-"""
15- 
16-from itertools import pairwise
17- 
18-import pytest
19-import torch
20- 
21-from torchtitan_npu.models.common.restore import DOC_CHUNK_LAYOUT
22-from torchtitan_npu.models.deepseek_v4 import _make_v4_config
23-from torchtitan_npu.models.deepseek_v4.attention import CompressedSparseInnerAttention
24-from torchtitan_npu.models.deepseek_v4.backend import with_npu_attention_backend
25-from torchtitan_npu.models.deepseek_v4.metadata import DeepSeekV4Metadata
26-from torchtitan_npu.models.deepseek_v4.sharding import set_deepseek_v4_sharding_config
27-from torchtitan_npu.override import _IS_A5
28-from torchtitan_npu.override.deepseek_v4.metadata import AicpuGeometry, AscV4Metadata
29-from torchtitan_npu.override.deepseek_v4.sparse_attn import asc_legacy
30-from torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc import AscCompressedSparseInnerAttention
31-from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import cp_shard_context_set
32- 
33-pytestmark = pytest.mark.usefixtures("dsv4")
34- 
35-_DIM, _HEADS, _HEAD_DIM = 32, 4, 8
36-_INDEX_N_HEADS, _INDEX_HEAD_DIM, _INDEX_TOPK, _WINDOW = 2, 8, 16, 128
37- 
38- 
39-def _positions_for(doc_lens) -> torch.Tensor:
40- return torch.cat([torch.arange(length) for length in doc_lens])
41- 
42- 
43-def _model_config(ratios: tuple[int, ...], *, ascendc: bool, geometry: dict | None = None):
44- config = _make_v4_config(
45- dim=_DIM,
46- n_layers=len(ratios),
47- vocab_size=64,
48- n_heads=_HEADS,
49- head_dim=_HEAD_DIM,
50- rope_head_dim=4,
51- q_lora_rank=16,
52- o_lora_rank=8,
53- n_groups=2,
54- compress_ratios=ratios,
55- window_size=_WINDOW,
56- norm_eps=1e-6,
57- index_n_heads=_INDEX_N_HEADS,
58- index_head_dim=_INDEX_HEAD_DIM,
59- index_topk=_INDEX_TOPK,
60- moe_inter_dim=16,
61- num_experts=2,
62- num_shared_experts=1,
63- top_k=1,
64- n_hash_layers=0,
65- route_norm=False,
66- route_scale=1.0,
67- load_balance_coeff=1e-3,
68- hc_mult=2,
69- sinkhorn_iters=2,
70- hc_eps=1e-6,
71- max_seq_len=_WINDOW * 2,
72- compress_rope_theta=10000.0,
73- original_seq_len=_WINDOW * 2,
74- num_mtp_layers=0,
75- )
76- # These tests exercise the explicitly retained geometry/carry backend.
77- config = with_npu_attention_backend(config)
78- # The sharding pass runs at config resolution, before the overrides.
79- set_deepseek_v4_sharding_config(config, enable_sp=False, enable_ep=False)
80- if ascendc:
81- for _, inner, parent, attr in list(config.traverse(CompressedSparseInnerAttention.Config)):
82- setattr(
83- parent,
84- attr,
85- asc_legacy(
86- inner,
87- **(
88- geometry
89- or {
90- "num_heads": _HEADS,
91- "head_dim": _HEAD_DIM,
92- "index_num_heads": _INDEX_N_HEADS,
93- "index_head_dim": _INDEX_HEAD_DIM,
94- }
95- ),
96- ),
97- )
98- return config
99- 
100- 
101-def _entry(model, ratio: int = 4, positions=None):
102- metadata = model._get_attention_metadata(_positions_for((_WINDOW, _WINDOW)) if positions is None else positions)
103- matches = [entry for entry in metadata.values() if entry.ratio == ratio]
104- assert len(matches) == 1
105- return matches[0]
106- 
107- 
108-def test_native_model_rejects_cp_even_with_aligned_documents():
109- from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_debugmodel
110- 
111- config = deepseek_v4_debugmodel()
112- config.parallelism.context_parallel_degree = 2
113- config.dataloader.dataset.dataset.processor.per_doc_alignment = 256
114- 
115- with pytest.raises(NotImplementedError, match="TP=CP=PP=1"):
116- with torch.device("meta"):
117- model = config.model.build()
118- model.parallelize(parallelism=config.parallelism)
119- 
120- 
121-def test_entries_are_built_per_geometry():
122- """One entry per (backend class, ratio), and every layer dispatches by its own key."""
123- model = _model_config((1, 1, 4, 128), ascendc=False).build()
124- 
125- metadata = model._get_attention_metadata(_positions_for((128, 128)))
126- 
127- assert {ratio for _, ratio in metadata} == {1, 4, 128}
128- entry = metadata[(CompressedSparseInnerAttention.Config, 4)]
129- assert type(entry) is DeepSeekV4Metadata and entry.ratio == 4
130- # The row grid lives on the sliding-window frame; the pool grid is this entry's own fold of it,
131- # and an unpooled geometry has no pool at all. At one degree nothing is moved or restored.
132- assert entry.swa_k.cu_seqlens.tolist() == [0, 128, 256]
133- assert entry.cmp_k is not None and entry.cmp_k.cu_seqlens.tolist() == [0, 32, 64]
134- assert metadata[(CompressedSparseInnerAttention.Config, 1)].cmp_k is None
135- assert entry.cp is None
136- keys = {layer.attention.attention_metadata_key for layer in model.layers.values()}
137- assert {key[1] for key in keys} == {1, 4, 128}
138- assert all(metadata[key].ratio == key[1] for key in keys)
139- 
140- 
141-@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"])
142-def test_attention_without_cp_matches_independent_samples(batch_size, monkeypatch):
143- """No-CP attention must preserve independent document rows and their gradients.
144- 
145- The folded row packs what used to be batch samples as documents, so the
146- oracle applies the same initialized layer to each document separately.
147- """
148- seq_len = 8
149- with torch.random.fork_rng(devices=[]):
150- torch.manual_seed(42)
151- model = _model_config((1,), ascendc=True).build()
152- attention = model.layers["0"].attention
153- attention.init_states(buffer_device=torch.device("cpu"))
154- 
155- def cpu_window_attention(q, swa_k, attn_sink, *, attention_metadata, **kwargs):
156- # The fused kernel is unavailable on CPU, while attn-gym's packed reference
157- # addresses one row. Isolate only that kernel with per-document dense
158- # causal math; RoPE and all input/output projections remain production code.
159- del kwargs
160- assert attention_metadata.cp is None
161- cu = attention_metadata.q.cu_seqlens.to(torch.long).tolist()
162- total = q.size(0)
163- scores = torch.einsum("thd,sd->ths", q.float(), swa_k.float()) * attention.inner_attention.softmax_scale
164- allow = torch.zeros(total, total, dtype=torch.bool)
165- for start, end in pairwise(cu):
166- allow[start:end, start:end] = torch.ones(end - start, end - start, dtype=torch.bool).tril()
167- scores = scores.masked_fill(~allow[:, None, :], float("-inf"))
168- sink = attn_sink[None, :, None].expand(*scores.shape[:-1], 1)
169- probabilities = torch.cat((scores, sink), dim=-1).softmax(dim=-1)[..., :-1]
170- return torch.einsum("ths,sd->thd", probabilities, swa_k)
171- 
172- monkeypatch.setattr(attention.inner_attention, "forward", cpu_window_attention)
173- values = torch.linspace(-1.0, 1.0, batch_size * seq_len * _DIM).reshape(batch_size * seq_len, _DIM)
174- x = values.clone().requires_grad_()
175- positions = _positions_for((seq_len,) * batch_size)
176- entry = model._get_attention_metadata(positions)[attention.attention_metadata_key]
177- # The folded row is one packed row: ``batch_size`` is its own count, not the
178- # number of documents that were packed into it.
179- assert entry.batch_size == 1
180- # At one degree the query frame is the row's own grid and every document is a
181- # batch sample here; the KV frame addresses that same row.
182- assert entry.q.cu_seqlens.tolist() == [row * seq_len for row in range(batch_size + 1)]
183- assert entry.swa_k.cu_seqlens.tolist() == entry.q.cu_seqlens.tolist()
184- parameters = tuple(attention.parameters())
185- upstream = torch.linspace(0.25, 1.25, x.numel()).reshape_as(x)
186- 
187- output = attention(x, entry, positions)
188- assert output.shape == (batch_size * seq_len, _DIM)
189- gradients = torch.autograd.grad((output * upstream).sum(), (x, *parameters))
190- 
191- # Distinct documents have no cross-row attention. Applying the same initialized
192- # layer to each document separately supplies the batch-composition oracle, including
193- # the sum of the individual parameter gradients for the same scalar objective.
194- expected_outputs, expected_input_gradients = [], []
195- expected_parameter_gradients = [torch.zeros_like(parameter) for parameter in parameters]
196- for row in range(batch_size):
197- slab = slice(row * seq_len, (row + 1) * seq_len)
198- sample = values[slab].clone().requires_grad_()
199- sample_positions = _positions_for((seq_len,))
200- sample_entry = model._get_attention_metadata(sample_positions)[attention.attention_metadata_key]
201- expected = attention(sample, sample_entry, sample_positions)
202- sample_gradients = torch.autograd.grad((expected * upstream[slab]).sum(), (sample, *parameters))
203- expected_outputs.append(expected)
204- expected_input_gradients.append(sample_gradients[0])
205- for accumulated, gradient in zip(expected_parameter_gradients, sample_gradients[1:], strict=True):
206- accumulated.add_(gradient)
207- 
208- torch.testing.assert_close(output, torch.cat(expected_outputs), rtol=1e-5, atol=1e-6)
209- torch.testing.assert_close(gradients[0], torch.cat(expected_input_gradients), rtol=1e-5, atol=1e-6)
210- for actual, expected in zip(gradients[1:], expected_parameter_gradients, strict=True):
211- torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6)
212- 
213- 
214-def test_the_fused_entry_carries_its_geometry_and_records(dsv4):
215- """The fused core's config builds the packed contract and its kernel records."""
216- dsv4.cann_ops.calls.clear()
217- model = _model_config((1, 4, 128), ascendc=True).build()
218- 
219- metadata = model._get_attention_metadata(_positions_for((128, 128, 128, 128)))
220- 
221- geometry = AicpuGeometry(
222- num_heads=_HEADS,
223- head_dim=_HEAD_DIM,
224- window_size=_WINDOW,
225- index_topk=_INDEX_TOPK,
226- index_num_heads=_INDEX_N_HEADS,
227- index_head_dim=_INDEX_HEAD_DIM,
228- )
229- for (cls, ratio), entry in metadata.items():
230- assert cls is AscCompressedSparseInnerAttention.Config and entry.ratio == ratio
231- assert isinstance(entry, AscV4Metadata)
232- assert entry.aicpu_metadata.geometry == geometry
233- assert entry.aicpu_metadata.sparse_attn.fwd is not None
234- assert entry.aicpu_metadata.sparse_attn.bwd is not None
235- assert entry.q is not None and entry.swa_k is not None
236- assert entry.cmp_k is None if ratio == 1 else entry.cmp_k is not None
237- # The fused core never reads ``slots``: its builder skips the reference-only
238- # S x (S / ratio) HCA matrix even for the ratio-128 geometry.
239- assert entry.slots is None
240- if ratio == 4:
241- assert entry.aicpu_metadata.lightning_indexer.fwd is not None
242- else:
243- assert entry.aicpu_metadata.lightning_indexer.fwd is None
244- smla = [call for call in dsv4.cann_ops.calls if call[0] == "sparse_flash_mla_metadata"]
245- assert len(smla) == 3
246- assert {call[2]["cmp_ratio"] for call in smla} == {1, 4, 128}
247- 
248- 
249-def test_only_the_reference_builds_the_hca_selection():
250- """``slots`` is the reference core's precomputed selection, not the fused core's.
251- 
252- The reference forward reads it (``kv_indices`` for a geometry without a selector); the
253- fused core's HCA branch runs full-causal on the compressed pool and never touches it, so
254- its builder passes ``build_slots=False`` and the ``S x (S / ratio)`` int64 matrix -- 64 GiB
255- at S=1M, ratio=128 -- is never materialised on the fused path.
256- """
257- positions = _positions_for((128, 128))
258- reference = _entry(_model_config((128,), ascendc=False).build(), 128, positions)
259- assert reference.slots is not None
260- assert reference.slots.shape == (1, 256, 2)
261- 
262- fused = _entry(_model_config((128,), ascendc=True).build(), 128, positions)
263- assert fused.slots is None
264- 
265- 
266-class _FakeCPMesh:
267- """The 1-D mesh contract the metadata's CP transform reads."""
268- 
269- ndim = 1
270- device_type = "cpu"
271- 
272- def __init__(self, rank: int, world_size: int):
273- self._rank = rank
274- self._world_size = world_size
275- 
276- def size(self, dim: int | None = None) -> int:
277- return self._world_size
278- 
279- def get_local_rank(self) -> int:
280- return self._rank
281- 
282- 
283-def _prepare_for_rank(attention_metadata, positions, *, rank: int, cp_size: int = 2):
284- with cp_shard_context_set(
285- cp_mesh=_FakeCPMesh(rank, cp_size),
286- load_balancer_type=DOC_CHUNK_LAYOUT,
287- positions=positions,
288- ):
289- return type(attention_metadata).prepare_cp_metadata(attention_metadata, permutation=None)
290- 
291- 
292-def _prefix(lengths: torch.Tensor) -> torch.Tensor:
293- """The frame of a per-document prefix: the running sum of the reach, from zero."""
294- return torch.cat([torch.zeros(1, dtype=torch.int32), torch.cumsum(lengths, 0).to(torch.int32)])
295- 
296- 
297-def test_the_fused_cp_transform_rebuilds_rank_local_frames(dsv4, monkeypatch):
298- """The CP half rebuilds this rank's frames and records from the global row."""
299- from torchtitan_npu.override.deepseek_v4.sparse_attn import ascendc
300- 
301- built: list[torch.Tensor] = []
302- 
303- def recording_smla_metadata(*args, **kwargs):
304- built.append(kwargs["cu_seqlens_q"])
305- return torch.tensor([kwargs["cu_seqlens_q"][-1].item()], dtype=torch.int32)
306- 
307- monkeypatch.setattr(ascendc, "sparse_flash_mla_metadata", recording_smla_metadata)
308- positions = _positions_for((_WINDOW, _WINDOW // 2))
309- model = _model_config((1, 4), ascendc=True).build()
310- 
311- global_metadata = _entry(model, 4, positions)
312- row = torch.tensor([0, _WINDOW, _WINDOW + _WINDOW // 2], dtype=torch.int32)
313- chunk = torch.diff(row) // 2
314- 
315- rank_metadata = [_prepare_for_rank(global_metadata, positions, rank=rank) for rank in range(2)]
316- for rank, metadata in enumerate(rank_metadata):
317- # The row stays the whole row; the queries are this rank's chunks.
318- _prefix_of_reach = _prefix((rank + 1) * chunk)
319- assert metadata.cmp_k is not None
320- assert torch.equal(metadata.q.cu_seqlens, (row // 2).to(torch.int32))
321- assert torch.equal(metadata.q.seqused, chunk)
322- # The key frames are the ones the kernels read: the row itself where they honour
323- # ``seqused``, the reach where they anchor their mask at the frame's end.
324- expected_window = row if _IS_A5 else _prefix_of_reach
325- assert torch.equal(metadata.swa_k.cu_seqlens, expected_window)
326- assert torch.equal(metadata.swa_k.seqused, (rank + 1) * chunk)
327- expected_pool = (row // 4).to(torch.int32) if _IS_A5 else _prefix_of_reach // 4
328- assert torch.equal(metadata.cmp_k.cu_seqlens, expected_pool)
329- assert torch.equal(metadata.cmp_k.seqused, ((rank + 1) * chunk) // 4)
330- assert metadata.ratio == 4
331- assert metadata.aicpu_metadata.sparse_attn.fwd is not global_metadata.aicpu_metadata.sparse_attn.fwd
332- assert metadata.aicpu_metadata.geometry == global_metadata.aicpu_metadata.geometry
333- assert metadata.cp is not None and metadata.cp.restore.exchange is not None
334- # The restore is rank-dependent even though the row is.
335- assert rank_metadata[0].position_k.tolist() != rank_metadata[1].position_k.tolist()
336- 
337- 
338-def test_the_inner_attention_and_selector_own_the_cp_boundary():
339- """The core gathers its KV streams; the selector gathers the index keys it scores.
340- 
341- Both conversions are the V4.1 ``S(1) -> R`` pattern, declared by the modules the layer
342- calls directly (there is no wrapper between them any more).
343- """
344- config = _model_config((4,), ascendc=True)
345- attention = config.layers[0].attention
346- core_sharding = attention.inner_attention.sharding_config
347- assert core_sharding is not None
348- names = set(core_sharding.in_src_shardings)
349- assert not names & {"idx_q", "idx_k", "idx_w"}
350- assert {"q", "swa_k", "cmp_k", "topk_indices", "topk_scores", "attn_sink"} <= names
351- # Positional forward args are (q, swa_k, attn_sink): the KV streams are gathered on the
352- # way in, so their destination placement is the whole row.
353- core_row = core_sharding.in_dst_shardings
354- assert core_row["swa_k"] != core_sharding.in_src_shardings["swa_k"]
355- assert core_row["cmp_k"] != core_sharding.in_src_shardings["cmp_k"]
356- 
357- selector_sharding = attention.lightning_indexer.sharding_config
358- assert selector_sharding is not None
359- assert set(selector_sharding.in_src_shardings) == {"idx_q", "idx_k", "idx_w"}
360- assert selector_sharding.in_dst_shardings["idx_k"] != selector_sharding.in_src_shardings["idx_k"]
@@ -1,429 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2-#
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.
5- 
6-"""CPU oracle at the CANN boundary, with real configs and document metadata.
7- 
8-The fused compressor is CP-agnostic: it compresses the local stream it is handed, addressed by
9-that stream's own ``cu_seqlens``. Under context parallelism the ratio-4 overlap's carry is
10-``CarryExchange``'s job, so the CP cases here compose the exchange with the same kernel module
11-and compare each rank's kept blocks with the whole row's pool.
12-"""
13- 
14-import copy
15-import importlib
16-import sys
17-import types
18-from itertools import pairwise
19- 
20-import pytest
21-import torch
22-import torch.nn.functional as F
23-from torchtitan.config import OverrideConfig, apply_overrides
24- 
25-from torchtitan_npu.models.common.carry_exchange import CarryExchange
26-from torchtitan_npu.models.deepseek_v4 import _debugmodel as _native_debugmodel
27-from torchtitan_npu.models.deepseek_v4 import _make_v4_config
28-from torchtitan_npu.models.deepseek_v4.backend import with_npu_attention_backend
29-from torchtitan_npu.models.deepseek_v4.compressor import (
30- Compressor,
31- CompressorImplementation,
32-)
33-from torchtitan_npu.models.deepseek_v4.metadata import build_v4_metadata
34-from torchtitan_npu.models.deepseek_v4.sharding import set_deepseek_v4_sharding_config
35-from torchtitan_npu.override.deepseek_v4.compressor import ascendc
36-from torchtitan_npu.override.deepseek_v4.metadata import AicpuGeometry
37-from torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc import build_aicpu_metadata
38- 
39-_FUSED_GEOMETRY = AicpuGeometry(
40- num_heads=16,
41- head_dim=512,
42- window_size=8,
43- index_topk=16,
44- index_num_heads=8,
45- index_head_dim=128,
46-)
47- 
48- 
49-def _debugmodel():
50- return with_npu_attention_backend(_native_debugmodel())
51- 
52- 
53-def _positions(cu: torch.Tensor) -> torch.Tensor:
54- """A packed row's document-relative positions, from its boundaries."""
55- return torch.cat([torch.arange(end - start) for start, end in pairwise(cu.tolist())])
56- 
57- 
58-def _entry(cu: torch.Tensor, ratio: int):
59- """One geometry's model entry: the row and this ratio's fold of it."""
60- return build_v4_metadata(_positions(cu), ratio, cu_seq_q=cu)
61- 
62- 
63-def _fused_entry(cu: torch.Tensor, ratio: int = 4):
64- """One geometry's fused entry: the model entry plus its records."""
65- return build_aicpu_metadata(_entry(cu, ratio), geometry=_FUSED_GEOMETRY)
66- 
67- 
68-def _tiny_config():
69- """A two-layer stack with one compressed (ratio-4) layer, cheap to build."""
70- config = _make_v4_config(
71- dim=32,
72- n_layers=2,
73- vocab_size=64,
74- n_heads=4,
75- head_dim=8,
76- rope_head_dim=4,
77- q_lora_rank=16,
78- o_lora_rank=8,
79- n_groups=2,
80- compress_ratios=(1, 4),
81- window_size=128,
82- norm_eps=1e-6,
83- index_n_heads=2,
84- index_head_dim=8,
85- index_topk=16,
86- moe_inter_dim=16,
87- num_experts=2,
88- num_shared_experts=1,
89- top_k=1,
90- n_hash_layers=0,
91- route_norm=False,
92- route_scale=1.0,
93- load_balance_coeff=1e-3,
94- hc_mult=2,
95- sinkhorn_iters=2,
96- hc_eps=1e-6,
97- max_seq_len=256,
98- compress_rope_theta=10000.0,
99- original_seq_len=256,
100- )
101- # The sharding pass runs at config resolution, before the overrides.
102- config = with_npu_attention_backend(config)
103- set_deepseek_v4_sharding_config(config, enable_sp=False, enable_ep=False)
104- return config
105- 
106- 
107-@pytest.mark.parametrize("reverse", [False, True], ids=["compressor-first", "compressor-last"])
108-def test_compressor_override_composes_with_norm_and_rope(monkeypatch, reverse):
109- from torchtitan_npu.override.common.rms_norm import AscRMSNorm
110- from torchtitan_npu.override.common.rope import AscComplexRoPE
111- 
112- registry = importlib.import_module("torchtitan.config.override")
113- monkeypatch.setattr(registry, "_REGISTRY", registry._REGISTRY.copy())
114- cfg = _debugmodel()
115- imports = [
116- "torchtitan_npu.override.deepseek_v4.compressor.legacy_asc",
117- "torchtitan_npu.override.common.rms_norm.asc",
118- "torchtitan_npu.override.common.rope.asc_complex",
119- ]
120- apply_overrides(OverrideConfig(imports=imports[::-1] if reverse else imports), cfg)
121- compressors = [node for _, node, _, _ in cfg.traverse(Compressor.Config)]
122- assert compressors
123- for node in compressors:
124- assert type(node) is Compressor.Config
125- assert isinstance(node.implementation, ascendc.AscCompressor.Config)
126- assert isinstance(node.norm, AscRMSNorm.Config)
127- assert isinstance(node.rope, AscComplexRoPE.Config)
128- assert all(
129- type(node.implementation) is CompressorImplementation.Config
130- for _, node, _, _ in _debugmodel().traverse(Compressor.Config)
131- )
132- 
133- 
134-def _document_pool(x, wkv, wgate, ape, cu, ratio):
135- outputs = []
136- width = wkv.shape[0] // (2 if ratio == 4 else 1)
137- for start, end in pairwise(cu):
138- values = F.linear(x[start:end].float(), wkv.float())
139- scores = F.linear(x[start:end].float(), wgate.float())
140- for offset in range(0, (end - start) // ratio * ratio, ratio):
141- current_values = values[offset : offset + ratio, -width:]
142- current_scores = scores[offset : offset + ratio, -width:] + ape[:, -width:]
143- if ratio == 4 and offset:
144- current_values = torch.cat((values[offset - ratio : offset, :width], current_values))
145- current_scores = torch.cat((scores[offset - ratio : offset, :width] + ape[:, :width], current_scores))
146- outputs.append((current_values * current_scores.softmax(0)).sum(0))
147- return torch.stack(outputs)
148- 
149- 
150-def _postprocess(module, pooled, positions):
151- normalized = F.rms_norm(pooled, (module.head_dim,), module.norm.weight, module.norm.eps)
152- return module.rope(normalized[:, None, :], positions=positions)[:, 0, :]
153- 
154- 
155-@pytest.fixture
156-def compressor_factory(monkeypatch):
157- registry = importlib.import_module("torchtitan.config.override")
158- with monkeypatch.context() as scoped, torch.random.fork_rng(devices=[]):
159- scoped.setattr(registry, "_REGISTRY", registry._REGISTRY.copy())
160- fake_module = types.ModuleType("compressor")
161- fake_module.compressor = lambda *args, **kwargs: pytest.fail("unexpected CANN compressor call")
162- scoped.setitem(sys.modules, "cann_ops_transformer.ops.compressor", fake_module)
163- torch.manual_seed(93)
164- 
165- def build(ratio, indexer=False):
166- cfg = _debugmodel()
167- apply_overrides(OverrideConfig(imports=["torchtitan_npu.override.deepseek_v4.compressor.legacy_asc"]), cfg)
168- attention = cfg.layers[2 if ratio == 4 else 3].attention
169- compressor_cfg = attention.indexer.compressor if indexer else attention.compressor
170- compressor_cfg.wkv.in_features = 1024
171- compressor_cfg.wgate.in_features = 1024
172- module = compressor_cfg.build()
173- assert isinstance(module.implementation, ascendc.AscCompressor)
174- module.init_states(buffer_device=torch.device("cpu"))
175- module.wkv.to(torch.float16)
176- module.wgate.to(torch.float16)
177- module.norm.to(torch.float16)
178- return module
179- 
180- try:
181- yield build
182- finally:
183- torch._dynamo.reset()
184- 
185- 
186-@pytest.mark.parametrize(
187- "ratio,indexer", [(4, False), (4, True), (128, False)], ids=["c4-attention", "c4-indexer", "c128"]
188-)
189-@pytest.mark.parametrize("api", ["torch-op", "python-wrapper"])
190-@pytest.mark.parametrize("ape_dtype", [torch.float32, torch.bfloat16])
191-@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"])
192-def test_compressor_cann_schema_document_outputs_and_gradients(
193- compressor_factory, monkeypatch, ratio, indexer, api, ape_dtype, batch_size
194-):
195- calls = []
196- lengths = [2 * ratio, ratio, 2 * ratio] * batch_size
197- 
198- def fake_cann(
199- x,
200- wkv,
201- wgate,
202- state_cache,
203- ape,
204- cmp_ratio=4,
205- *,
206- state_block_table=None,
207- cu_seqlens=None,
208- seqused=None,
209- start_pos=None,
210- coff=1,
211- cache_mode=1,
212- ):
213- assert torch.is_grad_enabled()
214- calls.append(cmp_ratio)
215- assert x.dtype == wkv.dtype == wgate.dtype == torch.float16
216- assert ape.dtype == state_cache.dtype == torch.float32
217- assert x.shape[1] == wkv.shape[1] == wgate.shape[1] == 1024
218- assert wkv is module.wkv.weight and wgate is module.wgate.weight
219- torch.testing.assert_close(ape, module.ape.float())
220- block_size = 8 if cmp_ratio == 4 else 16
221- assert state_cache.shape == (1, block_size, 2 * coff * module.head_dim)
222- # The port builds the all-zero tiling table from the stream's own shape symbols (the
223- # model-level interface never sees it); a host maximum would go stale on the next batch.
224- assert state_block_table.shape[0] == len(lengths)
225- assert state_block_table.shape[1] == max((sum(lengths) + block_size - 1) // block_size, 1)
226- assert not state_block_table.any() and start_pos is None and cache_mode == 1
227- torch.testing.assert_close(cu_seqlens, boundaries)
228- torch.testing.assert_close(seqused, torch.tensor(lengths, dtype=torch.int32))
229- pooled = (2 * _document_pool(x, wkv, wgate, ape, cu, cmp_ratio) + perturbation).to(x.dtype)
230- # Poison unused TND capacity so consuming it fails output comparisons.
231- return torch.cat((pooled, pooled.new_full((len(lengths), module.head_dim), float("nan"))))
232- 
233- if api == "torch-op":
234- monkeypatch.setattr(
235- torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False
236- )
237- else:
238- monkeypatch.setattr(torch.ops, "cann_ops_transformer", types.SimpleNamespace())
239- monkeypatch.setattr(sys.modules["cann_ops_transformer.ops.compressor"], "compressor", fake_cann)
240- 
241- module = compressor_factory(ratio, indexer)
242- module.ape = torch.nn.Parameter(module.ape.detach().to(ape_dtype), requires_grad=module.ape.requires_grad)
243- module.wgate.weight.requires_grad_(not indexer)
244- reference = copy.deepcopy(module)
245- cu = [0]
246- for length in lengths:
247- cu.append(cu[-1] + length)
248- boundaries = torch.tensor(cu, dtype=torch.int32)
249- positions = _positions(boundaries)
250- metadata = _entry(boundaries, ratio)
251- generator = torch.Generator().manual_seed(21)
252- x = (
253- (torch.randn(cu[-1], module.wkv.in_features, generator=generator) * 0.1)
254- .half()
255- .requires_grad_()
256- )
257- reference_x = x.detach().clone().requires_grad_()
258- perturbation = torch.linspace(-0.02, 0.03, module.head_dim)
259- 
260- actual = module(x, positions, cu_seqlens=metadata.swa_k.cu_seqlens)
261- # Match the operator boundary: accumulate APE gradients in FP32, then cast
262- # once back to the BF16 parameter instead of rounding each sliced contribution.
263- raw = _document_pool(
264- reference_x, reference.wkv.weight, reference.wgate.weight, reference.ape.float(), cu, ratio
265- )
266- expected = _postprocess(reference, (2 * raw + perturbation).half(), positions[::ratio])
267- upstream_grad = torch.randn(actual.shape, generator=generator).half()
268- actual.backward(upstream_grad)
269- expected.backward(upstream_grad)
270- 
271- assert calls == [ratio]
272- torch.testing.assert_close(actual, expected, rtol=0, atol=0)
273- torch.testing.assert_close(x.grad, reference_x.grad, rtol=0.006, atol=0.004)
274- for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"):
275- actual_grad = module.get_parameter(name).grad
276- expected_grad = reference.get_parameter(name).grad
277- if expected_grad is None:
278- assert actual_grad is None
279- else:
280- torch.testing.assert_close(actual_grad, expected_grad, rtol=0.006, atol=0.004)
281- 
282- 
283-@pytest.mark.parametrize("api", ["torch-op", "python-wrapper"])
284-@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"])
285-def test_compressor_available_api_compiles(compressor_factory, monkeypatch, api, batch_size):
286- def fake_cann(x, wkv, wgate, state_cache, ape, cmp_ratio=4, **kwargs):
287- width = wkv.shape[0] // 2
288- values = F.linear(x.float(), wkv.float()).reshape(-1, cmp_ratio, 2, width)
289- scores = F.linear(x.float(), wgate.float()).reshape_as(values) + ape.reshape(1, cmp_ratio, 2, width)
290- return (values[:, :, 1] * scores[:, :, 1].softmax(dim=1)).sum(dim=1).to(x.dtype)
291- 
292- if api == "torch-op":
293- monkeypatch.setattr(
294- torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False
295- )
296- else:
297- monkeypatch.setattr(torch.ops, "cann_ops_transformer", types.SimpleNamespace())
298- monkeypatch.setattr(sys.modules["cann_ops_transformer.ops.compressor"], "compressor", fake_cann)
299- module = compressor_factory(4).float()
300- reference = copy.deepcopy(module)
301- boundaries = torch.arange(batch_size + 1, dtype=torch.int32) * 8
302- positions = _positions(boundaries)
303- metadata = _entry(boundaries, 4)
304- x = torch.randn(batch_size * 8, module.wkv.in_features, generator=torch.Generator().manual_seed(17)).requires_grad_()
305- reference_x = x.detach().clone().requires_grad_()
306- 
307- actual = torch.compile(module, backend="aot_eager", fullgraph=True, dynamic=True)(
308- x, positions, cu_seqlens=metadata.swa_k.cu_seqlens
309- )
310- expected = reference(reference_x, positions, cu_seqlens=metadata.swa_k.cu_seqlens)
311- torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6)
312- actual.sum().backward()
313- expected.sum().backward()
314- # The crossing-document fixture also changes the CP-segment / full-document GEMM
315- # batch shapes, so the gradient accumulation order differs; the measured worst
316- # at c128 is 1.43e-05 (2/524288 elements), still fp32 rounding noise.
317- torch.testing.assert_close(x.grad, reference_x.grad, rtol=1e-4, atol=2e-5)
318- for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"):
319- torch.testing.assert_close(
320- module.get_parameter(name).grad, reference.get_parameter(name).grad, rtol=1e-4, atol=1e-5
321- )
322- 
323- 
324-class _FakeMesh:
325- """The two mesh methods the carry reads."""
326- 
327- def __init__(self, rank: int, size: int):
328- self._rank, self._size = rank, size
329- 
330- def get_local_rank(self) -> int:
331- return self._rank
332- 
333- def size(self) -> int:
334- return self._size
335- 
336- 
337-@pytest.mark.parametrize("ratio,indexer", [(4, False), (4, True)], ids=["c4-attention", "c4-indexer"])
338-def test_compressor_cp_carry_trim_matches_the_global_pool(compressor_factory, monkeypatch, ratio, indexer):
339- """The exchange's keep-set is exactly this rank's block range of the whole row's pool.
340- 
341- Two equal documents span the four slabs, so ranks 1 and 3 carry the previous rank's last
342- block; rank 2's slab starts at the second document's edge and carries it as a segment of its
343- own. The fake kernel is the same per-document pool the unsharded tests use, so any
344- difference is the CP framing itself.
345- """
346- from torchtitan_npu.models.common import carry_exchange as carry_module
347- 
348- cp_size = 4
349- total = 16 * ratio
350- cu = [0, 8 * ratio, total]
351- boundaries = torch.tensor(cu, dtype=torch.int32)
352- positions = _positions(boundaries)
353- slab = total // cp_size
354- 
355- module = compressor_factory(ratio, indexer).float()
356- reference = copy.deepcopy(module)
357- generator = torch.Generator().manual_seed(42)
358- x = (torch.randn(total, module.wkv.in_features, generator=generator) * 0.1).requires_grad_()
359- reference_x = x.detach().clone().requires_grad_()
360- shards = x.reshape(cp_size, slab, -1)
361- current = [0]
362- 
363- def fake_all_to_all(send, *, output_split_sizes, input_split_sizes, group):
364- del group
365- # ``all_to_all_single`` splits dim 0, so the block travels as ``[ratio, D]`` rows.
366- assert send.size(0) == sum(input_split_sizes)
367- sources = [source for source, split in enumerate(output_split_sizes) if split]
368- if not sources:
369- return send[:0]
370- assert sources == [current[0] - 1]
371- source = sources[0]
372- first = source * slab
373- if send.dtype == torch.int32:
374- return positions[..., first + slab - ratio : first + slab].reshape(-1).to(torch.int32)
375- return shards[source][-ratio:]
376- 
377- def fake_cann(
378- x_flat,
379- wkv,
380- wgate,
381- state_cache,
382- ape,
383- cmp_ratio=4,
384- *,
385- state_block_table=None,
386- cu_seqlens=None,
387- seqused=None,
388- start_pos=None,
389- coff=1,
390- cache_mode=1,
391- ):
392- del state_cache, state_block_table, seqused, start_pos, cache_mode
393- assert coff == (2 if cmp_ratio == 4 else 1)
394- return _document_pool(x_flat, wkv, wgate, ape, cu_seqlens.tolist(), cmp_ratio).to(x_flat.dtype)
395- 
396- monkeypatch.setattr(carry_module, "all_to_all_single", fake_all_to_all)
397- monkeypatch.setattr(module.implementation, "_compressor_fn", fake_cann)
398- 
399- global_raw = _document_pool(reference_x, reference.wkv.weight, reference.wgate.weight, reference.ape, cu, ratio)
400- global_positions = torch.cat(
401- [torch.arange(0, (end - start) // ratio * ratio, ratio) for start, end in pairwise(cu)]
402- )
403- global_expected = _postprocess(reference, global_raw, global_positions)
404- losses, expected_losses = [], []
405- for rank in range(cp_size):
406- current[0] = rank
407- exchange = CarryExchange(CarryExchange.Config(ratio=ratio))
408- exchange.group = _FakeMesh(rank, cp_size)
409- carry = exchange(
410- shards[rank : rank + 1],
411- positions[None, rank * slab : (rank + 1) * slab],
412- boundaries,
413- )
414- pooled = module(carry.x.squeeze(0), carry.positions.squeeze(0), cu_seqlens=carry.cu_seqlens)
415- pooled = pooled.narrow(0, carry.trim, pooled.size(0) - carry.trim)
416- actual = pooled
417- expected = global_expected[rank * (slab // ratio) : (rank + 1) * (slab // ratio)]
418- # The CP segments and full documents use different CPU GEMM batch shapes.
419- torch.testing.assert_close(actual, expected, rtol=1e-5, atol=2e-6)
420- grad = torch.randn(actual.shape, generator=generator)
421- losses.append((actual * grad).sum())
422- expected_losses.append((expected * grad).sum())
423- sum(losses).backward()
424- sum(expected_losses).backward()
425- torch.testing.assert_close(x.grad, reference_x.grad, rtol=1e-4, atol=1e-5)
426- for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"):
427- torch.testing.assert_close(
428- module.get_parameter(name).grad, reference.get_parameter(name).grad, rtol=1e-4, atol=1e-5
429- )
@@ -214,3 +214,35 @@ def test_compiled_example_preserves_the_current_training_guard():
214 214 
215 with pytest.raises(NotImplementedError, match="NPU model compilation is not supported"):215 with pytest.raises(NotImplementedError, match="NPU model compilation is not supported"):
216 config.__post_init__()216 config.__post_init__()
217+ 
218+ 
219+def test_loader_selects_graph_recipe_and_preserves_npu_component_settings(monkeypatch):
220+ from torchtitan.experiments.graph_trainer.chunked_loss import ChunkedLossWrapperWithParamGrads
221+ from torchtitan.experiments.graph_trainer.trainer import GraphTrainer
222+ 
223+ from torchtitan_npu.config import TrainingConfig
224+ from torchtitan_npu.models.deepseek_v4.model import GraphTrainerDeepSeekV4Model
225+ 
226+ monkeypatch.delenv("DSV4_PER_DOC_ALIGNMENT", raising=False)
227+ config = ConfigLoader().load(
228+ [
229+ "--module",
230+ "torchtitan_npu_recipes.graph_trainer.deepseek_v4",
231+ "--config",
232+ "graph_trainer_deepseek_v4_debugmodel",
233+ ]
234+ )
235+ 
236+ assert isinstance(config, GraphTrainer.Config)
237+ assert isinstance(config.model, GraphTrainerDeepSeekV4Model.Config)
238+ assert isinstance(config.training, TrainingConfig)
239+ assert config.training.steps == 100
240+ assert config.training.disable_cuda_graphs
241+ assert config.model.local_compile_regions == []
242+ assert isinstance(config.loss, ChunkedLossWrapperWithParamGrads.Config)
243+ assert config.optim.optimizer._muon_profile is not None
244+ assert config.override.imports == ["torchtitan_npu.override.common.rope.workaround"]
245+ assert config.dataloader.dataset.dataset.processor.per_doc_alignment == 128
246+ assert not hasattr(config, "extension")
247+ assert not hasattr(config, "sdc")
248+ assert not hasattr(config, "anticipatory")
@@ -111,21 +111,3 @@ def test_dsv4_muon_indexer_query_uses_per_head_block_sharding():
111 indexer = model_spec.layers[2].attention.indexer111 indexer = model_spec.layers[2].attention.indexer
112 assert indexer is not None112 assert indexer is not None
113 assert indexer_dp_sharding.block_sizes == (indexer.index_head_dim,)113 assert indexer_dp_sharding.block_sizes == (indexer.index_head_dim,)
114- 
115- 
116-def test_graph_trainer_conversion_strips_only_npu_top_level_extension():
117- conversion_path = _ROOT / "torchtitan_npu/models/deepseek_v4/graph_trainer.py"
118- registry_path = _ROOT / "torchtitan_npu_recipes/graph_trainer/deepseek_v4.py"
119- conversion_source = _function_source(conversion_path, "to_graph_trainer_config")
120- 
121- assert "isinstance(base_config, TrainerEx.Config)" in conversion_source
122- assert "for config_field in fields(Trainer.Config)" in conversion_source
123- 
124- for graph_recipe in (
125- "graph_trainer_deepseek_v4_debugmodel",
126- "graph_trainer_deepseek_v4_flash",
127- "graph_trainer_deepseek_v4_flash_43layers_16experts",
128- "graph_trainer_deepseek_v4_pro",
129- "graph_trainer_deepseek_v4_pro_61layers_32experts",
130- ):
131- assert "use_npu_config" not in _function_source(registry_path, graph_recipe)
@@ -8,4 +8,6 @@
8- **目标状态:** 与 `patches` 一起自包含,只依赖标准库、上游包和本层内部模块;新增代码不得直接依赖 `extensions`、`override` 或 `ops`。8- **目标状态:** 与 `patches` 一起自包含,只依赖标准库、上游包和本层内部模块;新增代码不得直接依赖 `extensions`、`override` 或 `ops`。
9- **当前债务:** DeepSeek-V4/V4.1 的配置、并行化、checkpoint 适配仍直接使用 extension 或 override,Qwen3.5 也直接使用模型专属 override。它们的收敛范围记录在架构 Agent Note,不作为新增依赖的先例。9- **当前债务:** DeepSeek-V4/V4.1 的配置、并行化、checkpoint 适配仍直接使用 extension 或 override,Qwen3.5 也直接使用模型专属 override。它们的收敛范围记录在架构 Agent Note,不作为新增依赖的先例。
10- 模型需要 NPU kernel 时应经上游或 override 注入,不新增对 `ops` 的直接依赖。10- 模型需要 NPU kernel 时应经上游或 override 注入,不新增对 `ops` 的直接依赖。
11+- DeepSeek-V4 使用原生模型配置,按需选择 compressor / inner-attention override;不再提供 `backend.py` 的旧版整层注意力与布局转换入口。
12+- DeepSeek-V4 在模块构造时声明自身参数的精度保留集合;共享 FSDP 策略由 `patches/torchtitan/` 的上游 #5774 运行期回移提供。不得在模型中复制 FSDP/MTP sharding 或恢复按全局 FQN 匹配的精度列表。
11- `train.py` 只导入 `torchtitan_npu` 以激活 patches 与 extensions,不导入其他 `torchtitan_npu` 子模块;真正训练入口来自上游 TorchTitan。13- `train.py` 只导入 `torchtitan_npu` 以激活 patches 与 extensions,不导入其他 `torchtitan_npu` 子模块;真正训练入口来自上游 TorchTitan。
@@ -3,23 +3,17 @@
3# This source code is licensed under the BSD-style license found in the3# 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-"""Native per-parameter precision for decoder models with MTP layers."""6+"""Translate explicit per-model dtype selections to native FSDP callbacks."""
7 7 
8from __future__ import annotations8from __future__ import annotations
9 9 
10from typing import TYPE_CHECKING10from typing import TYPE_CHECKING
11 11 
12-from torchtitan.distributed.fsdp import apply_fsdp_to_decoder
13- 
14if TYPE_CHECKING:12if TYPE_CHECKING:
15 from collections.abc import Callable, Mapping13 from collections.abc import Callable, Mapping
16 14 
17 import torch15 import torch
18 from torch import nn16 from torch import nn
19- from torch.distributed.device_mesh import DeviceMesh
20- from torch.distributed.fsdp import DataParallelMeshDims
21- from torchtitan.config.parallelism import FSDPSymmMemScope
22- from torchtitan.models.common.decoder import Decoder
23 17 
24 18 
25def make_param_dtype_override_fn(19def make_param_dtype_override_fn(
@@ -47,54 +41,3 @@ def make_param_dtype_override_fn(
47 return dtypes_by_id.get(id(param))41 return dtypes_by_id.get(id(param))
48 42 
49 return override43 return override
50- 
51- 
52-def apply_fsdp_to_mtp_decoder(
53- model: Decoder,
54- dp_mesh: DeviceMesh,
55- param_dtype: torch.dtype,
56- reduce_dtype: torch.dtype,
57- pp_enabled: bool,
58- cpu_offload: bool = False,
59- reshard_after_forward_policy: str = "default",
60- ep_degree: int = 1,
61- edp_mesh: DeviceMesh | None = None,
62- dp_mesh_dims: DataParallelMeshDims | None = None,
63- edp_mesh_dims: DataParallelMeshDims | None = None,
64- symm_mem_scope: FSDPSymmMemScope = None,
65- *,
66- param_dtype_override_fn: Callable[[nn.Parameter], torch.dtype | None] | None = None,
67-) -> None:
68- """Forward native precision overrides through the released MTP sharding layout.
69- 
70- TorchTitan v0.4.0's MTP helper does not forward the decoder callback. Keep
71- its temporary layer aliases while delegating all FSDP behavior upstream.
72- """
73- mtp_layer_keys = []
74- try:
75- mtp_layers = getattr(model, "mtp_layers", None)
76- if mtp_layers is not None:
77- first_mtp_layer_id = len(model.layers)
78- for index, layer in enumerate(mtp_layers):
79- key = str(first_mtp_layer_id + index)
80- model.layers[key] = layer
81- mtp_layer_keys.append(key)
82- 
83- apply_fsdp_to_decoder(
84- model,
85- dp_mesh,
86- param_dtype=param_dtype,
87- reduce_dtype=reduce_dtype,
88- pp_enabled=pp_enabled,
89- cpu_offload=cpu_offload,
90- reshard_after_forward_policy=reshard_after_forward_policy,
91- ep_degree=ep_degree,
92- edp_mesh=edp_mesh,
93- dp_mesh_dims=dp_mesh_dims,
94- edp_mesh_dims=edp_mesh_dims,
95- symm_mem_scope=symm_mem_scope,
96- param_dtype_override_fn=param_dtype_override_fn,
97- )
98- finally:
99- for key in mtp_layer_keys:
100- del model.layers[key]
@@ -17,20 +17,19 @@ from torchtitan.models.common.decoder_sharding import (
17 pre_lm_head_norm_sharding_config,17 pre_lm_head_norm_sharding_config,
18 token_embedding_sharding_config,18 token_embedding_sharding_config,
19)19)
20-from torchtitan.models.common.param_init import depth_scaled_std
21from torchtitan.models.deepseek_v4.flavors import (20from torchtitan.models.deepseek_v4.flavors import (
22 _build_mtp_layers as _upstream_build_mtp_layers,21 _build_mtp_layers as _upstream_build_mtp_layers,
23)22)
24from torchtitan.models.deepseek_v4.flavors import (23from torchtitan.models.deepseek_v4.flavors import (
25 _build_v4_layers as _upstream_build_v4_layers,24 _build_v4_layers as _upstream_build_v4_layers,
26)25)
26+from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
27from torchtitan.models.deepseek_v4.sharding import hc_head_sharding_config27from torchtitan.models.deepseek_v4.sharding import hc_head_sharding_config
28 28 
29from torchtitan_npu.models.common.activation import LimitedSwiGLU29from torchtitan_npu.models.common.activation import LimitedSwiGLU
30 30 
31from .attention import DeepSeekV4Attention as Attention31from .attention import DeepSeekV4Attention as Attention
32from .attention import UnitScaleRMSNorm32from .attention import UnitScaleRMSNorm
33-from .mhc import HcHead, HcPost, HcPre
34from .model import (33from .model import (
35 DeepSeekV4Model,34 DeepSeekV4Model,
36 DeepSeekV4TransformerBlock,35 DeepSeekV4TransformerBlock,
@@ -58,14 +57,8 @@ __all__ = [
58 "model_registry",57 "model_registry",
59]58]
60 59 
61-_LINEAR_INIT = {
62- "weight": partial(nn.init.trunc_normal_, std=0.02),
63- "bias": nn.init.zeros_,
64-}
65_NORM_INIT = {"weight": nn.init.ones_}60_NORM_INIT = {"weight": nn.init.ones_}
66_EMBEDDING_INIT = {"weight": partial(nn.init.normal_, std=1.0)}61_EMBEDDING_INIT = {"weight": partial(nn.init.normal_, std=1.0)}
67-_APE_INIT = {"ape": partial(nn.init.trunc_normal_, std=0.02)}
68-_SINK_INIT = {"attn_sink": partial(nn.init.trunc_normal_, std=0.02)}
69_HC_PARAM_INIT = {62_HC_PARAM_INIT = {
70 "hc_fn": partial(nn.init.trunc_normal_, std=0.02),63 "hc_fn": partial(nn.init.trunc_normal_, std=0.02),
71 "hc_base": partial(nn.init.trunc_normal_, std=0.02),64 "hc_base": partial(nn.init.trunc_normal_, std=0.02),
@@ -81,21 +74,6 @@ def _output_linear_init(dim: int) -> dict[str, Callable]:
81 }74 }
82 75 
83 76 
84-def _depth_init(layer_id: int) -> dict[str, Callable]:
85- return {
86- "weight": partial(nn.init.trunc_normal_, std=depth_scaled_std(0.02, layer_id)),
87- "bias": nn.init.zeros_,
88- }
89- 
90- 
91-def _depth_experts_init(layer_id: int) -> dict[str, Callable]:
92- return {
93- "w1_EFD": partial(nn.init.trunc_normal_, std=0.02),
94- "w2_EDF": partial(nn.init.trunc_normal_, std=depth_scaled_std(0.02, layer_id)),
95- "w3_EFD": partial(nn.init.trunc_normal_, std=depth_scaled_std(0.02, layer_id)),
96- }
97- 
98- 
99# SwiGLU gate/up clamp shared by all DSV4 flavors; 10.0 is the transformers77# SwiGLU gate/up clamp shared by all DSV4 flavors; 10.0 is the transformers
100# config default (``swiglu_limit: float = 10.0``) and the inference repo's78# config default (``swiglu_limit: float = 10.0``) and the inference repo's
101# ``config.json`` value. Zero disables the clamp.79# ``config.json`` value. Zero disables the clamp.
@@ -1,156 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-# SPDX-License-Identifier: BSD-3-Clause
3- 
4-"""Legacy NPU geometry layout for older experiments and checkpoints.
5- 
6-Maintained V4 recipes keep upstream attention and use compressor/inner-attention
7-overrides directly. These converters remain only for explicit legacy callers.
8-"""
9- 
10-from __future__ import annotations
11- 
12-from copy import deepcopy
13-from dataclasses import dataclass, replace
14-from typing import TYPE_CHECKING
15- 
16-from torchtitan.config import derive
17-from torchtitan.models.common.linear import Linear
18-from torchtitan.models.deepseek_v4.attention import DeepSeekV4Attention
19- 
20-from torchtitan_npu.models.common.carry_exchange import CarryExchange
21-from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear
22- 
23-from .attention import NPUAttention, NPUCompressedSparseInnerAttention, UnitScaleRMSNorm
24-from .compressor import LightningIndexer, NPUCompressor, NPUIndexer
25-from .model import DeepSeekV4Model
26-from .sharding import set_deepseek_v4_attention_sharding
27-from .state_dict_adapter import DeepSeekV4StateDictAdapter
28- 
29-if TYPE_CHECKING:
30- from torchtitan.models.deepseek_v4.compressor import Compressor, Indexer
31- 
32- 
33-class NPUBackendDeepSeekV4Model(DeepSeekV4Model):
34- """Upstream V4 model/block math with the NPU attention checkpoint layout."""
35- 
36- state_dict_adapter_cls = DeepSeekV4StateDictAdapter
37- 
38- @dataclass(kw_only=True, slots=True)
39- class Config(DeepSeekV4Model.Config):
40- pass
41- 
42- 
43-def _split_rope(config, *, head_dim: int, rope_head_dim: int):
44- # The package's split-aware RoPE config is installed before model loading.
45- return replace(config, split=head_dim - rope_head_dim)
46- 
47- 
48-def _to_npu_compressor(config: Compressor.Config) -> NPUCompressor.Config:
49- return derive(
50- config,
51- NPUCompressor.Config,
52- rope=_split_rope(config.rope, head_dim=config.head_dim, rope_head_dim=config.rope_head_dim),
53- carry_exchange=CarryExchange.Config(ratio=config.compress_ratio),
54- )
55- 
56- 
57-def _to_npu_indexer(config: Indexer.Config) -> NPUIndexer.Config:
58- return derive(
59- config,
60- NPUIndexer.Config,
61- rope=_split_rope(config.rope, head_dim=config.index_head_dim, rope_head_dim=config.rope_head_dim),
62- compressor=_to_npu_compressor(config.compressor),
63- )
64- 
65- 
66-def to_npu_attention_config(
67- config: DeepSeekV4Attention.Config,
68- *,
69- enable_sp: bool = False,
70-) -> NPUAttention.Config:
71- """Translate native attention storage/metadata without mutating its config.
72- 
73- The backend owns document geometry, carry exchange and the selector node
74- consumed by the existing NPU component overrides. Its sink is a bare
75- ``[heads]`` parameter; the upstream reference keeps ``[heads, 1]`` in a
76- Linear module. Grouped output projection weights have the same flattened
77- storage in both implementations.
78- """
79- if isinstance(config, NPUAttention.Config):
80- return deepcopy(config)
81- if not isinstance(config, DeepSeekV4Attention.Config):
82- raise TypeError(f"Expected a native DeepSeekV4Attention.Config, got {type(config).__name__}")
83- if type(config.wo_a) is not Linear.Config or type(config.attn_sink) is not Linear.Config:
84- raise ValueError("Select the NPU attention backend before converting output projection or sink linears")
85- if config.wo_a.bias or config.wo_a.num_linears != 1 or config.attn_sink.bias:
86- raise ValueError("The NPU attention backend requires the native bias-free grouped projection and sink layout")
87- if config.inner_attention.aux_loss is not None:
88- raise ValueError(
89- "The NPU attention backend owns its indexer objective; construct the native config "
90- "with indexer_loss_coeff=0 before selecting the backend."
91- )
92- config = deepcopy(config)
93- # Upstream denotes window-only attention by ratio 0; NPU geometry uses 1.
94- compress_ratio = max(1, config.compress_ratio)
95- compressor = config.compressor if config.compress_ratio == 4 else config.compressor_128
96- if config.compress_ratio > 1 and compressor is None:
97- raise ValueError(f"Compression ratio {config.compress_ratio} requires its compressor config")
98- if config.wo_a.out_features % config.n_groups:
99- raise ValueError("The grouped output projection width must be divisible by n_groups")
100- sink_init = (config.attn_sink.param_init or {}).get("weight")
101- param_init = dict(config.param_init or {})
102- if sink_init is not None:
103- param_init["attn_sink"] = sink_init
104- result = NPUAttention.Config(
105- n_heads=config.n_heads,
106- head_dim=config.head_dim,
107- rope_head_dim=config.rope_head_dim,
108- q_lora_rank=config.q_lora_rank,
109- n_groups=config.n_groups,
110- compress_ratio=compress_ratio,
111- norm_eps=config.norm_eps,
112- rope=_split_rope(config.rope, head_dim=config.head_dim, rope_head_dim=config.rope_head_dim),
113- wq_a=config.wq_a,
114- q_norm=config.q_norm,
115- q_head_norm=UnitScaleRMSNorm.Config(normalized_shape=config.head_dim, eps=config.norm_eps),
116- wq_b=config.wq_b,
117- wkv=config.wkv,
118- kv_norm=config.kv_norm,
119- wo_a=BatchedLinear.Config(
120- n_heads=config.n_groups,
121- in_features=config.wo_a.in_features,
122- out_features=config.wo_a.out_features // config.n_groups,
123- param_init=config.wo_a.param_init,
124- ),
125- wo_b=config.wo_b,
126- compressor=_to_npu_compressor(compressor) if compressor is not None else None,
127- indexer=_to_npu_indexer(config.indexer) if config.indexer is not None else None,
128- lightning_indexer=(
129- LightningIndexer.Config(index_topk=config.inner_attention.index_topk)
130- if config.indexer is not None
131- else None
132- ),
133- inner_attention=NPUCompressedSparseInnerAttention.Config(
134- window_size=config.inner_attention.window_size,
135- compress_ratio=compress_ratio,
136- softmax_scale=config.inner_attention.softmax_scale,
137- index_topk=config.inner_attention.index_topk,
138- ),
139- param_init=param_init or None,
140- )
141- set_deepseek_v4_attention_sharding(result, enable_sp=enable_sp)
142- return result
143- 
144- 
145-def with_npu_attention_backend(
146- config: DeepSeekV4Model.Config,
147- *,
148- enable_sp: bool = False,
149-) -> NPUBackendDeepSeekV4Model.Config:
150- """Select the NPU attention and state layout before applying child overrides."""
151- config = deepcopy(config)
152- for layer in (*config.layers, *(config.mtp_layers or ())):
153- attention = to_npu_attention_config(layer.attention, enable_sp=enable_sp)
154- layer.attention = attention # pyrefly: ignore [bad-assignment]
155- # The backend state adapter owns a concrete list of configured MTP stages.
156- return derive(config, NPUBackendDeepSeekV4Model.Config, mtp_layers=config.mtp_layers or [])
@@ -1,32 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2-#
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.
5- 
6-from __future__ import annotations
7- 
8-from dataclasses import fields
9-from typing import TYPE_CHECKING
10- 
11-from torchtitan.trainer import Trainer
12- 
13-from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
14- 
15-if TYPE_CHECKING:
16- from torchtitan.experiments.graph_trainer.trainer import GraphTrainer
17- 
18- from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4Model
19- 
20- 
21-def to_graph_trainer_config(
22- base_config: Trainer.Config,
23- model_config_cls: type[DeepSeekV4Model.Config],
24-) -> GraphTrainer.Config:
25- """Project DSV4's NPU recipe config onto GraphTrainer's upstream schema."""
26- if isinstance(base_config, TrainerEx.Config):
27- base_config = Trainer.Config(
28- **{config_field.name: getattr(base_config, config_field.name) for config_field in fields(Trainer.Config)}
29- )
30- from torchtitan.experiments.graph_trainer.configs import to_graph_trainer_config as _to_graph_trainer_config
31- 
32- return _to_graph_trainer_config(base_config, model_config_cls)
@@ -17,12 +17,15 @@ from torchtitan_npu.models.common.deepseek_lora import (
17from torchtitan_npu.models.common.deepseek_lora import (17from torchtitan_npu.models.common.deepseek_lora import (
18 DeepSeekLoRATransform as DeepSeekLoRATransform,18 DeepSeekLoRATransform as DeepSeekLoRATransform,
19)19)
20+from torchtitan_npu.models.common.deepseek_lora import (
21+ DeepSeekPEFTAdapter as DeepSeekPEFTAdapter,
22+)
20from torchtitan_npu.models.common.deepseek_lora import (23from torchtitan_npu.models.common.deepseek_lora import (
21 deepseek_v4_lora_transform as deepseek_v4_lora_transform,24 deepseek_v4_lora_transform as deepseek_v4_lora_transform,
22)25)
23- 26+from torchtitan_npu.models.common.deepseek_lora import (
24-from .peft_adapter import DeepSeekPEFTAdapter as DeepSeekPEFTAdapter27+ is_lora_parameter as is_lora_parameter,
25-from .peft_adapter import is_lora_parameter as is_lora_parameter28+)
26 29 
27MODULE_PATHS = (30MODULE_PATHS = (
28 ("lm_head", "lm_head", "head"),31 ("lm_head", "lm_head", "head"),
@@ -1,15 +0,0 @@
1-# Copyright (c) Meta Platforms, Inc. and affiliates.
2-#
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.
5- 
6-"""TorchTitan's DeepSeek-V4 mHC reference components.
7- 
8-NPU implementations are selected by the corresponding configuration overrides.
9-The package patch restores DeepSeek's additive epsilon before Sinkhorn balancing
10-while retaining the upstream components (pytorch/torchtitan#5975).
11-"""
12- 
13-__all__ = ["HcHead", "HcPost", "HcPre", "HcSplitSinkhorn"]
14- 
15-from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre, HcSplitSinkhorn
@@ -8,9 +8,6 @@ from typing import TYPE_CHECKING, cast
8 8 
9import torch9import torch
10from torch import nn10from torch import nn
11-from torchtitan.config import TORCH_DTYPE_MAP, TrainingConfig
12-from torchtitan.config.parallelism import ParallelismConfig
13-from torchtitan.distributed.parallelism_context import ParallelismContext
14from torchtitan.models.common.flops import get_nparams_and_active_nparams11from torchtitan.models.common.flops import get_nparams_and_active_nparams
15from torchtitan.models.deepseek_v4.model import DeepSeekV4TransformerBlock as DeepSeekV4TransformerBlock12from torchtitan.models.deepseek_v4.model import DeepSeekV4TransformerBlock as DeepSeekV4TransformerBlock
16 13 
@@ -45,46 +42,12 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder):
45 from torchtitan.models.common.aux_loss import register_aux_loss_zero_hook42 from torchtitan.models.common.aux_loss import register_aux_loss_zero_hook
46 from torchtitan.models.common.moe import register_moe_load_balancing_hook43 from torchtitan.models.common.moe import register_moe_load_balancing_hook
47 44 
48- from .peft_adapter import is_lora_parameter45+ from torchtitan_npu.models.common.deepseek_lora import is_lora_parameter
49 46 
50 if not any(is_lora_parameter(name) for model in model_parts for name, _ in model.named_parameters()):47 if not any(is_lora_parameter(name) for model in model_parts for name, _ in model.named_parameters()):
51 register_moe_load_balancing_hook(optimizers, model_parts, parallelism_context)48 register_moe_load_balancing_hook(optimizers, model_parts, parallelism_context)
52 register_aux_loss_zero_hook(optimizers, model_parts, parallelism_context)49 register_aux_loss_zero_hook(optimizers, model_parts, parallelism_context)
53 50 
54- def _apply_fsdp(
55- self,
56- *,
57- parallelism_context: ParallelismContext,
58- training: TrainingConfig,
59- parallelism: ParallelismConfig,
60- ) -> None:
61- from torchtitan.distributed.fsdp import resolve_fsdp_mesh, resolve_sparse_fsdp_mesh
62- 
63- from torchtitan_npu.models.common.fsdp import apply_fsdp_to_mtp_decoder, make_param_dtype_override_fn
64- 
65- dp_mesh, dp_mesh_dims = resolve_fsdp_mesh(parallelism_context)
66- edp_mesh, edp_mesh_dims = resolve_sparse_fsdp_mesh(parallelism_context)
67- 
68- from .parallelize import _dsv4_param_dtypes
69- 
70- apply_fsdp_to_mtp_decoder(
71- # The helper requires the decoder/layers/MTP structure, shared by
72- # this implementation and the upstream DeepSeek V4 model.
73- self,
74- dp_mesh,
75- param_dtype=TORCH_DTYPE_MAP[training.mixed_precision_param],
76- reduce_dtype=TORCH_DTYPE_MAP[training.mixed_precision_reduce],
77- pp_enabled=parallelism_context.pp_enabled,
78- cpu_offload=training.enable_cpu_offload,
79- reshard_after_forward_policy=parallelism.fsdp_reshard_after_forward,
80- ep_degree=parallelism_context.ep,
81- edp_mesh=edp_mesh,
82- dp_mesh_dims=dp_mesh_dims,
83- edp_mesh_dims=edp_mesh_dims,
84- symm_mem_scope=parallelism.fsdp_symm_mem_scope,
85- param_dtype_override_fn=make_param_dtype_override_fn(self, _dsv4_param_dtypes(self, training)),
86- )
87- 
88 @dataclass(kw_only=True, slots=True)51 @dataclass(kw_only=True, slots=True)
89 class Config(DeepSeekV4MTPDecoder.Config):52 class Config(DeepSeekV4MTPDecoder.Config):
90 vocab_size: int53 vocab_size: int
@@ -132,6 +95,20 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder):
132 95 
133 def __init__(self, config: Config):96 def __init__(self, config: Config):
134 super().__init__(config)97 super().__init__(config)
98+ mtp_layers = cast("nn.ModuleList | None", self.mtp_layers)
99+ for layer in (*self.layers.values(), *(mtp_layers if mtp_layers is not None else ())):
100+ # The training router policy also covers adapter/quantization children.
101+ router = cast("nn.Module | None", getattr(layer.feed_forward, "router", None))
102+ if router is not None:
103+ for module in router.modules():
104+ names = tuple(name for name, parameter in module._parameters.items() if parameter is not None)
105+ setattr(module, "_preserve_dtype_params", names) # noqa: B010 -- API backported on existing modules
106+ attention = cast("nn.Module", layer.attention)
107+ sink = cast("nn.Module | nn.Parameter", attention.attn_sink)
108+ if isinstance(sink, nn.Parameter):
109+ setattr(attention, "_preserve_dtype_params", ("attn_sink",)) # noqa: B010
110+ else:
111+ setattr(sink, "_preserve_dtype_params", ("weight",)) # noqa: B010
135 112 
136 113 
137class GraphTrainerDeepSeekV4Model(DeepSeekV4Model):114class GraphTrainerDeepSeekV4Model(DeepSeekV4Model):
@@ -34,14 +34,13 @@ from torchtitan.models.deepseek_v3.mtp import (
34 MTPLoss,34 MTPLoss,
35 roll_mtp_sequence,35 roll_mtp_sequence,
36)36)
37+from torchtitan.models.deepseek_v4.mhc import HcHead # noqa: TC002 -- runtime config annotation
37from torchtitan.models.deepseek_v4.model import DeepSeekV4Model as TorchTitanV4Model38from torchtitan.models.deepseek_v4.model import DeepSeekV4Model as TorchTitanV4Model
38from torchtitan.models.deepseek_v4.mtp import MTPBlock39from torchtitan.models.deepseek_v4.mtp import MTPBlock
39 40 
40from torchtitan_npu.models.common.attention_metadata import AttentionMetadataMap, GeometryAttentionMetadataMixin41from torchtitan_npu.models.common.attention_metadata import AttentionMetadataMap, GeometryAttentionMetadataMixin
41from torchtitan_npu.models.common.linear import SharedLinear42from torchtitan_npu.models.common.linear import SharedLinear
42 43 
43-from .mhc import HcHead # noqa: TC001
44- 
45 44 
46class MTPBatch(NamedTuple):45class MTPBatch(NamedTuple):
47 """Per-depth MTP tensors with depth stored in the last dimension."""46 """Per-depth MTP tensors with depth stored in the last dimension."""
@@ -8,12 +8,10 @@ from __future__ import annotations
8 8 
9from typing import TYPE_CHECKING, Any9from typing import TYPE_CHECKING, Any
10 10 
11-import torch
12from torchtitan.experiments.graph_trainer.common_utils import (11from torchtitan.experiments.graph_trainer.common_utils import (
13 annotate_module_fqns,12 annotate_module_fqns,
14 annotate_moe_ep_regions,13 annotate_moe_ep_regions,
15 apply_simple_fsdp,14 apply_simple_fsdp,
16- matches_module_fqn_pattern,
17)15)
18from torchtitan.experiments.graph_trainer.compile import (16from torchtitan.experiments.graph_trainer.compile import (
19 apply_compile as apply_graph_trainer_compile,17 apply_compile as apply_graph_trainer_compile,
@@ -26,81 +24,10 @@ if TYPE_CHECKING:
26 from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig24 from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig
27 25 
28 from torchtitan_npu.models.deepseek_v4.model import (26 from torchtitan_npu.models.deepseek_v4.model import (
29- DeepSeekV4Model,
30 GraphTrainerDeepSeekV4Model,27 GraphTrainerDeepSeekV4Model,
31 )28 )
32 29 
33 30 
34-def _dsv4_param_dtypes(
35- model: DeepSeekV4Model,
36- training: TrainingConfig,
37-) -> dict[str, torch.dtype]:
38- """Return the fqn-fp32 policy map for DSV4 SmoE hyper-connection and MoE router parameters."""
39- 
40- def matches_any(fqn: str, patterns: tuple[str, ...]) -> bool:
41- """Check if a module/parameter FQN matches any of the fnmatch patterns."""
42- clean = ".".join(part for part in fqn.split(".") if part != "_checkpoint_wrapped_module")
43- return any(matches_module_fqn_pattern(pattern, clean) for pattern in patterns)
44- 
45- fp32_module_fqns = (
46- "layers.*.hc_attn_pre",
47- "layers.*.hc_ffn_pre",
48- "layers.*.feed_forward.router",
49- "layers.*.hc_head",
50- "mtp_layers.*.hc_attn_pre",
51- "mtp_layers.*.hc_ffn_pre",
52- "mtp_layers.*.feed_forward.router",
53- "mtp_layers.*.hc_head",
54- "hc_head",
55- )
56- fp32_parameter_fqns = (
57- "layers.*.attention.compressor.ape",
58- "layers.*.attention.compressor_128.ape",
59- "layers.*.attention.compressor_128.ape",
60- "layers.*.attention.indexer.compressor.ape",
61- "mtp_layers.*.attention.compressor.ape",
62- "mtp_layers.*.attention.compressor_128.ape",
63- "mtp_layers.*.attention.compressor_128.ape",
64- "mtp_layers.*.attention.indexer.compressor.ape",
65- # Learned per-head softmax logits: created FP32 in attention.py and
66- # required FP32 by the attention kernels.
67- "layers.*.attention.attn_sink",
68- "layers.*.attention.attn_sink.weight",
69- "mtp_layers.*.attention.attn_sink",
70- "mtp_layers.*.attention.attn_sink.weight",
71- )
72- 
73- fp32_modules = [module for name, module in model.named_modules() if matches_any(name, fp32_module_fqns)]
74- fp32_param_ids = {id(param) for module in fp32_modules for param in module.parameters()}
75- 
76- overrides: dict[str, torch.dtype] = {}
77- for name, parameter in model.named_parameters(remove_duplicate=False):
78- if id(parameter) in fp32_param_ids or matches_any(name, fp32_parameter_fqns):
79- overrides[name] = torch.float32
80- 
81- return overrides
82- 
83- 
84-def parallelize_deepseek_v4(model, **kwargs):
85- """Apply upstream eager parallelization with DSV4 FP32 parameter policies."""
86- from torchtitan.models.base.model import BaseModel
87- 
88- return BaseModel.parallelize(model, **kwargs)
89- 
90- 
91-def annotate_deepseek_v4(model: GraphTrainerDeepSeekV4Model) -> None:
92- """Attach annotations to FX graph nodes for DeepSeek V4.
93- 
94- - Expert Parallel (EP) annotations: Tags "dispatch", "combine", and "compute"
95- regions in MoE for debugging purposes.
96- - Module FQN annotation: Tags each submodule's forward with its
97- fully-qualified name for downstream passes (bucketing, SAC region
98- boundaries, etc.).
99- """
100- annotate_moe_ep_regions()
101- annotate_module_fqns(model)
102- 
103- 
104def parallelize_graph_trainer_deepseek_v4(31def parallelize_graph_trainer_deepseek_v4(
105 model: GraphTrainerDeepSeekV4Model,32 model: GraphTrainerDeepSeekV4Model,
106 *,33 *,
@@ -125,7 +52,8 @@ def parallelize_graph_trainer_deepseek_v4(
125 "Context Parallel is not yet supported for DeepSeek V4 sparse attention in the GraphTrainer path."52 "Context Parallel is not yet supported for DeepSeek V4 sparse attention in the GraphTrainer path."
126 )53 )
127 54 
128- annotate_deepseek_v4(model)55+ annotate_moe_ep_regions()
56+ annotate_module_fqns(model)
129 57 
130 # SPMD declarations must be resolved even when every model-parallel axis is58 # SPMD declarations must be resolved even when every model-parallel axis is
131 # singleton; the non-graph path applies the same unconditional lifecycle.59 # singleton; the non-graph path applies the same unconditional lifecycle.
@@ -138,12 +66,9 @@ def parallelize_graph_trainer_deepseek_v4(
138 # pyrefly: ignore [bad-assignment]66 # pyrefly: ignore [bad-assignment]
139 model = apply_simple_fsdp(model, parallelism_context=parallelism_context, training=training)67 model = apply_simple_fsdp(model, parallelism_context=parallelism_context, training=training)
140 68 
141- # Apply compilation based on mode69+ apply_graph_trainer_compile(
142- # pyrefly: ignore [bad-assignment]
143- model = apply_graph_trainer_compile(
144 model,70 model,
145 compile_config=compile_config,71 compile_config=compile_config,
146 parallelism_context=parallelism_context,72 parallelism_context=parallelism_context,
147 )73 )
atomgit-bot
atomgit-botatomgit-bot23 days ago

🟡 Medium Priority

变更点:torchtitan_npu/models/deepseek_v4/parallelize.py 第 69-73 行把原来的 model = apply_graph_trainer_compile(model, ...)(原第 143 行,并带有 # pyrefly: ignore [bad-assignment] 抑制)改成不接收返回值的裸调用,随后第 74 行仍 return model。

契约影响:torchtitan.experiments.graph_trainer.compile.apply_compile 是一个“组装/包装”步骤(原注释为 “Apply compilation based on mode”),上游其它组装函数(同文件第 67 行 apply_simple_fsdp)都通过返回值传递结果,本仓 torchtitan_npu/models/deepseek_v4_1/parallelize.py 的编译封装同样以“返回值/就地编译”混合形态存在,因此该调用是否有返回值无法从本 diff 直接判定。

失效模式:若上游 apply_compile 按 mode 返回 torch.compile 包装后的模块(即返回新对象而非就地修改传入 model),本 diff 丢弃返回值后,parallelize_graph_trainer_deepseek_v4 会把 未编译 / 未植入自定义 pass pipeline 的 FSDP 模型 返回给 GraphTrainerDeepSeekV4Model.parallelize(model.py:130),训练仍然能跑、单测也不易发现,但 graph capture / region compile 被静默跳过,属于只影响性能与图训练语义的静默回归;若上游确实是就地编译且返回 None,则本改动反而修掉了旧代码把 None 赋回 model 的隐患。

建议:核实 torchtitan.experiments.graph_trainer.compile.apply_compile 是否返回编译后的模块;若返回新对象,应恢复 model = apply_graph_trainer_compile(model, ...)(含 pyrefly 抑制)以保证编译结果被传给调用方,否则在注释中明确说明该函数是就地编译以固定契约。

likedislike
Incorrect?
148- 
149 return model74 return model
@@ -1,11 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2-# SPDX-License-Identifier: BSD-3-Clause
3- 
4-"""V4 keeps the shared DeepSeek PEFT conversion; the implementation lives in common."""
5- 
6-from torchtitan_npu.models.common.deepseek_lora import (
7- DeepSeekPEFTAdapter,
8- is_lora_parameter,
9-)
10- 
11-__all__ = ["DeepSeekPEFTAdapter", "is_lora_parameter"]
@@ -10,7 +10,7 @@ from torchtitan.models.deepseek_v4.state_dict_adapter import (
10 DeepSeekV4StateDictAdapter as UpstreamDeepSeekV4StateDictAdapter,10 DeepSeekV4StateDictAdapter as UpstreamDeepSeekV4StateDictAdapter,
11)11)
12 12 
13-from torchtitan_npu.models.deepseek_v4.peft_adapter import DeepSeekPEFTAdapter, is_lora_parameter13+from torchtitan_npu.models.common.deepseek_lora import DeepSeekPEFTAdapter, is_lora_parameter
14 14 
15from .model import DeepSeekV4Model15from .model import DeepSeekV4Model
16 16 
@@ -18,8 +18,7 @@ and HcHead overrides target separate nodes and may coexist across families.
18"""18"""
19 19 
20from torchtitan.config import derive, override20from torchtitan.config import derive, override
21- 21+from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
22-from torchtitan_npu.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
23 22 
24from .ascendc import AscHcPost, AscHcPre23from .ascendc import AscHcPost, AscHcPre
25from .tilelang import TilelangHcHead, TilelangHcPost, TilelangHcPre24from .tilelang import TilelangHcHead, TilelangHcPost, TilelangHcPre
@@ -9,9 +9,9 @@ from dataclasses import dataclass
9 9 
10import torch10import torch
11import torch_npu11import torch_npu
12+from torchtitan.models.deepseek_v4.mhc import HcPost, HcPre
12 13 
13import torchtitan_npu.ops.ascendc.mhc # noqa: F40114import torchtitan_npu.ops.ascendc.mhc # noqa: F401
14-from torchtitan_npu.models.deepseek_v4.mhc import HcPost, HcPre
15from torchtitan_npu.override import _IS_A515from torchtitan_npu.override import _IS_A5
16 16 
17 17 
@@ -16,8 +16,8 @@ import torch
16from torch import Tensor16from torch import Tensor
17from torch.distributed.tensor import DTensor17from torch.distributed.tensor import DTensor
18from torch.nn import functional as F18from torch.nn import functional as F
19+from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
19 20 
20-from torchtitan_npu.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
21from torchtitan_npu.ops.tilelang import (21from torchtitan_npu.ops.tilelang import (
22 mhc_head_compute_mix_tilelang,22 mhc_head_compute_mix_tilelang,
23 tilelang_mhc_head_compute_mix_a5,23 tilelang_mhc_head_compute_mix_a5,
@@ -9,8 +9,8 @@ from dataclasses import dataclass
9 9 
10import torch10import torch
11import torch_npu11import torch_npu
12+from torchtitan.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
12 13 
13-from torchtitan_npu.models.deepseek_v4.mhc import HcHead, HcPost, HcPre
14from torchtitan_npu.ops.triton.mhc import (14from torchtitan_npu.ops.triton.mhc import (
15 mhc_post_bmm1_op,15 mhc_post_bmm1_op,
16 mhc_post_bmm2_op,16 mhc_post_bmm2_op,
@@ -36,6 +36,10 @@ if not hasattr(_pipelining, "PipelineStageInfo"):
36# entry order stop mattering. Drop it when the pin carries #5744.36# entry order stop mattering. Drop it when the pin carries #5744.
37import torchtitan.config # noqa: F40137import torchtitan.config # noqa: F401
38 38 
39+# Keep the released config classes while installing the shared precision API.
40+from .models import base # noqa: F401
41+from .distributed import fsdp # noqa: F401
42+ 
39from .components import metrics, optimizer # noqa: F40143from .components import metrics, optimizer # noqa: F401
40import torchtitan_npu.patches.torchtitan.distributed.checkpoint.filesystem # noqa: F40144import torchtitan_npu.patches.torchtitan.distributed.checkpoint.filesystem # noqa: F401
41 45 
@@ -0,0 +1,84 @@
1+# Copyright (c) Meta Platforms, Inc. and affiliates.
2+# All rights reserved.
3+#
4+# This source code is licensed under the BSD-style license found in the
5+# LICENSE file in the root directory of this source tree.
6+ 
7+# Upstream-PR: https://github.com/pytorch/torchtitan/pull/5774
8+ 
9+"""Apply module-owned precision through TorchTitan 0.4.0's native FSDP path.
10+ 
11+Retain the released decoder and MTP sharding implementations. Only policy
12+construction is backported; the config schemas and other precision consumers
13+remain on the pinned release. Remove this patch when the dependency includes
14+the upstream preservation API.
15+"""
16+ 
17+from functools import wraps
18+from inspect import signature
19+ 
20+import torch
21+import torchtitan.distributed.fsdp
22+import torchtitan.models.deepseek_v3.mtp
23+from torch import nn
24+from torch.distributed.fsdp import MixedPrecisionPolicy
25+from torchtitan.models.base.module import Module
26+ 
27+_original_apply_fsdp_to_decoder = torchtitan.distributed.fsdp.apply_fsdp_to_decoder
28+_decoder_signature = signature(_original_apply_fsdp_to_decoder)
29+ 
30+ 
31+def mixed_precision_policy(
32+ module: nn.Module,
33+ *,
34+ param_dtype: torch.dtype,
35+ reduce_dtype: torch.dtype,
36+ cast_forward_inputs: bool = True,
37+) -> MixedPrecisionPolicy:
38+ """Preserve declared parameters in the wider of their own and compute dtype."""
39+ preserved = {
40+ id(param)
41+ for _, param in Module.named_preserve_dtype_params(module) # pyrefly: ignore [missing-attribute]
42+ }
43+ 
44+ def param_dtype_override_fn(param: nn.Parameter) -> torch.dtype | None:
45+ return torch.promote_types(param.dtype, param_dtype) if id(param) in preserved else None
46+ 
47+ # The pinned Torch 2.15 provides this field; older CI images have 2.14 types.
48+ return MixedPrecisionPolicy(
49+ param_dtype=param_dtype,
50+ reduce_dtype=reduce_dtype,
51+ cast_forward_inputs=cast_forward_inputs,
52+ param_dtype_override_fn=param_dtype_override_fn if preserved else None, # pyrefly: ignore [unexpected-keyword]
53+ )
atomgit-bot
atomgit-botatomgit-bot23 days ago

🟡 Medium Priority

变更行:torchtitan_npu/patches/torchtitan/distributed/fsdp.py:47-52 无条件构造 MixedPrecisionPolicy(..., param_dtype_override_fn=param_dtype_override_fn ...)。

影响面:apply() 在模块导入时把这个包装函数挂到 torchtitan.distributed.fsdp.apply_fsdp_to_decoder 上,所有走上游 decoder FSDP 的模型(V4 主模型、models/deepseek_v4_1/parallelize.py、override/qwen3_5/parallelize.py)都会经过 mixed_precision_policy();注意即使 preserved 为空(如 Qwen3.5、V4.1 未声明 preserve 参数),这里的 MixedPrecisionPolicy(...) 构造仍会先执行。

失败模式:本仓库明确记载 param_dtype_override_fn 是 torch 2.15 才加入 MixedPrecisionPolicy 的参数 —— torchtitan_npu/extensions/torchtitan/distributed/fsdp.py:102-105 专门用 inspect.signature(MixedPrecisionPolicy).parameters 做存在性判断后才转发该 kwarg,注释写明"CI images that still run torch 2.14 cannot accept it";torchtitan_npu/patches/torchtitan/__init__.py:9-30 也为 torch 2.14 CI 打了 pipelining 兼容 stub。因此在 torch 2.14 环境下,任何一次 apply_fsdp_to_decoder 调用都会在 MixedPrecisionPolicy.__init__ 抛 TypeError: unexpected keyword argument 'param_dtype_override_fn',FSDP 构建整体失败,而旧代码路径(models/common/fsdp.py + extensions/.../fsdp.py 的带 guard 版本)在 2.14 上是可用的,属于本次改动引入的回归。

修复方向:与仓库既有实现保持一致 —— 只在 param_dtype_override_fn 存在于 MixedPrecisionPolicy 签名时才传入;更好的做法是包装器根本不需要构造 policy,直接返回 override 闭包即可(见下一条)。

建议:按 extensions/torchtitan/distributed/fsdp.py:102-105 的方式做签名探测:先构造 kwargs,if "param_dtype_override_fn" in inspect.signature(MixedPrecisionPolicy).parameters 再填入;或改为不构造 MixedPrecisionPolicy,直接返回 override 闭包供调用点使用。

likedislike
Incorrect?
54+ 
55+ 
56+@wraps(_original_apply_fsdp_to_decoder)
57+def _apply_fsdp_to_decoder(*args, **kwargs) -> None:
58+ bound = _decoder_signature.bind(*args, **kwargs)
59+ if bound.arguments.get("param_dtype_override_fn") is None:
60+ policy = mixed_precision_policy(
61+ bound.arguments["model"],
62+ param_dtype=bound.arguments["param_dtype"],
63+ reduce_dtype=bound.arguments["reduce_dtype"],
64+ cast_forward_inputs=False,
65+ )
66+ bound.arguments["param_dtype_override_fn"] = (
67+ policy.param_dtype_override_fn # pyrefly: ignore [missing-attribute]
68+ )
69+ _original_apply_fsdp_to_decoder(*bound.args, **bound.kwargs)
70+ 
71+ 
72+def apply() -> None:
73+ """Update the canonical function and the release's single captured binding."""
74+ if hasattr(torchtitan.distributed.fsdp, "mixed_precision_policy"):
75+ return
76+ torchtitan.distributed.fsdp.mixed_precision_policy = mixed_precision_policy # pyrefly: ignore [missing-attribute]
77+ torchtitan.distributed.fsdp.apply_fsdp_to_decoder = _apply_fsdp_to_decoder
78+ 
79+ # Decoder resolves its import at call time; MTP captures this one globally.
80+ # V4's captured MTP helper keeps the same function and reads this binding.
81+ torchtitan.models.deepseek_v3.mtp.apply_fsdp_to_decoder = _apply_fsdp_to_decoder
82+ 
83+ 
84+apply()
@@ -0,0 +1,6 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
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.
5+ 
6+from . import module # noqa: F401
@@ -0,0 +1,52 @@
1+# Copyright (c) Meta Platforms, Inc. and affiliates.
2+# All rights reserved.
3+#
4+# This source code is licensed under the BSD-style license found in the
5+# LICENSE file in the root directory of this source tree.
6+ 
7+# Upstream-PR: https://github.com/pytorch/torchtitan/pull/5774
8+ 
9+"""Backport module-owned precision declarations without replacing config schemas.
10+ 
11+TorchTitan 0.4.0's slotted config subclasses can already be imported when this
12+patch loads. Keep their identities and declare parameter names on built modules.
13+The iterator also honors explicit declarations on foreign ``nn.Module`` children,
14+which preserves the existing router policy across optional component adaptors.
15+Remove this patch when the pinned version provides the upstream config API.
16+"""
17+ 
18+from collections.abc import Iterator
19+ 
20+import torchtitan.models.base.module
21+from torch import nn
22+ 
23+ 
24+def _named_preserve_dtype_params(self: nn.Module) -> Iterator[tuple[str, nn.Parameter]]:
25+ """Yield declared own parameters, resolving their current objects by name."""
26+ for module_fqn, module in self.named_modules():
27+ names = getattr(module, "_preserve_dtype_params", ())
28+ if not names:
29+ continue
30+ parameters = {name: param for name, param in module._parameters.items() if param is not None}
31+ unknown = set(names) - parameters.keys()
32+ if unknown:
33+ raise ValueError(
34+ f"preserve_dtype_params names {sorted(unknown)} are not own parameters of "
35+ f"{type(module).__name__} at {module_fqn or '<root>'}. "
36+ f"Its parameters are {sorted(parameters)}."
37+ )
38+ for name in names:
39+ yield f"{module_fqn}.{name}" if module_fqn else name, parameters[name]
40+ 
41+ 
42+def apply() -> None:
43+ """Extend the existing class so previously imported components see the API."""
44+ if hasattr(torchtitan.models.base.module.Module, "named_preserve_dtype_params"):
45+ return
46+ torchtitan.models.base.module.Module._preserve_dtype_params = () # pyrefly: ignore [missing-attribute]
47+ torchtitan.models.base.module.Module.named_preserve_dtype_params = ( # pyrefly: ignore [missing-attribute]
48+ _named_preserve_dtype_params
49+ )
50+ 
51+ 
52+apply()
@@ -3,4 +3,4 @@
3# This source code is licensed under the BSD-style license found in the3# 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 . import mhc # noqa: F4016+from . import mhc, precision # noqa: F401
@@ -0,0 +1,40 @@
1+# Copyright (c) Meta Platforms, Inc. and affiliates.
2+# All rights reserved.
3+#
4+# This source code is licensed under the BSD-style license found in the
5+# LICENSE file in the root directory of this source tree.
6+ 
7+# Upstream-PR: https://github.com/pytorch/torchtitan/pull/5774
8+ 
9+"""Preserve native DeepSeek component precision on the 0.4.0 config schemas.
10+ 
11+These module defaults mirror the upstream config declarations. Native subclasses
12+and NPU component overrides inherit them without replacing imported config types.
13+Remove this patch when the dependency includes the upstream declarations.
14+"""
15+ 
16+import torchtitan.models.base.module
17+import torchtitan.models.deepseek_v4.compressor
18+import torchtitan.models.deepseek_v4.mhc
19+ 
20+ 
21+def apply() -> None:
22+ """Keep existing schemas and defer to native declarations after an upgrade."""
23+ if "preserve_dtype_params" in torchtitan.models.base.module.Module.Config.__dataclass_fields__:
24+ return
25+ torchtitan.models.deepseek_v4.mhc.HcPre._preserve_dtype_params = ( # pyrefly: ignore [missing-attribute]
26+ "hc_fn",
27+ "hc_base",
28+ "hc_scale",
29+ )
30+ torchtitan.models.deepseek_v4.mhc.HcHead._preserve_dtype_params = ( # pyrefly: ignore [missing-attribute]
31+ "hc_fn",
32+ "hc_base",
33+ "hc_scale",
34+ )
35+ torchtitan.models.deepseek_v4.compressor.Compressor._preserve_dtype_params = ( # pyrefly: ignore [missing-attribute] # noqa: E501
36+ "ape",
37+ )
38+ 
39+ 
40+apply()
@@ -453,7 +453,12 @@ def deepseek_v4_flash_lora_4k_a3() -> TrainerEx.Config:
453def _graph_example(*, a5: bool, full_model: bool = False) -> TrainerEx.Config:453def _graph_example(*, a5: bool, full_model: bool = False) -> TrainerEx.Config:
454 """Keep the graph recipe's policy while retaining the existing NPU guard."""454 """Keep the graph recipe's policy while retaining the existing NPU guard."""
455 from torchtitan.config import derive455 from torchtitan.config import derive
456- from torchtitan.experiments.graph_trainer.configs import EpOverlapConfig, GraphTrainerCompileConfig456+ from torchtitan.experiments.graph_trainer.configs import (
457+ EpOverlapConfig,
458+ GraphTrainerCompileConfig,
459+ to_graph_trainer_config,
460+ )
461+ from torchtitan.trainer import Trainer
457 462 
458 try:463 try:
459 from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import GraphTrainerEx464 from torchtitan_npu.extensions.torchtitan.experiments.graph_trainer import GraphTrainerEx
@@ -464,7 +469,6 @@ def _graph_example(*, a5: bool, full_model: bool = False) -> TrainerEx.Config:
464 "NPU GraphTrainer remains deferred: its existing slotted configuration "469 "NPU GraphTrainer remains deferred: its existing slotted configuration "
465 "bases have incompatible instance layouts in TorchTitan 0.4.0."470 "bases have incompatible instance layouts in TorchTitan 0.4.0."
466 ) from error471 ) from error
467- from torchtitan_npu.models.deepseek_v4.graph_trainer import to_graph_trainer_config
468 from torchtitan_npu.models.deepseek_v4.model import GraphTrainerDeepSeekV4Model472 from torchtitan_npu.models.deepseek_v4.model import GraphTrainerDeepSeekV4Model
469 from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import (473 from torchtitan_npu.patches.torchtitan.experiments.graph_trainer import (
470 functionalize_recompute_mutations as _functionalize_mutations,474 functionalize_recompute_mutations as _functionalize_mutations,
@@ -472,7 +476,7 @@ def _graph_example(*, a5: bool, full_model: bool = False) -> TrainerEx.Config:
472 476 
473 base = _flash_full(a5=a5) if full_model else _flash_8p(a5=a5)477 base = _flash_full(a5=a5) if full_model else _flash_8p(a5=a5)
474 base.compile = None478 base.compile = None
475- graph = to_graph_trainer_config(base, GraphTrainerDeepSeekV4Model.Config)479+ graph = to_graph_trainer_config(derive(base, Trainer.Config), GraphTrainerDeepSeekV4Model.Config)
476 graph.compile = GraphTrainerCompileConfig(480 graph.compile = GraphTrainerCompileConfig(
477 memory_policy="full",481 memory_policy="full",
478 pass_pipeline=f"{_functionalize_mutations.PASS_PIPELINE_NAME}+npu_auto_overlap",482 pass_pipeline=f"{_functionalize_mutations.PASS_PIPELINE_NAME}+npu_auto_overlap",
@@ -7,8 +7,11 @@ from __future__ import annotations
7 7 
8from typing import TYPE_CHECKING8from typing import TYPE_CHECKING
9 9 
10+from torchtitan.config import derive
11+from torchtitan.experiments.graph_trainer.configs import to_graph_trainer_config
12+from torchtitan.trainer import Trainer
13+ 
10from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager14from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager
11-from torchtitan_npu.models.deepseek_v4.graph_trainer import to_graph_trainer_config
12from torchtitan_npu.models.deepseek_v4.model import GraphTrainerDeepSeekV4Model15from torchtitan_npu.models.deepseek_v4.model import GraphTrainerDeepSeekV4Model
13from torchtitan_npu_recipes.models.deepseek_v4 import (16from torchtitan_npu_recipes.models.deepseek_v4 import (
14 deepseek_v4_debugmodel,17 deepseek_v4_debugmodel,
@@ -57,8 +60,11 @@ def graph_trainer_deepseek_v4_debugmodel(
57 )60 )
58 61 
59 config = to_graph_trainer_config(62 config = to_graph_trainer_config(
60- deepseek_v4_debugmodel(63+ derive(
61- num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path64+ deepseek_v4_debugmodel(
65+ num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path
66+ ),
67+ Trainer.Config,
62 ),68 ),
63 GraphTrainerDeepSeekV4Model.Config,69 GraphTrainerDeepSeekV4Model.Config,
64 )70 )
@@ -81,7 +87,12 @@ def graph_trainer_deepseek_v4_flash(
81) -> GraphTrainer.Config:87) -> GraphTrainer.Config:
82 """GraphTrainer config for the DeepSeek V4 Flash model"""88 """GraphTrainer config for the DeepSeek V4 Flash model"""
83 config = to_graph_trainer_config(89 config = to_graph_trainer_config(
84- deepseek_v4_flash(num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path),90+ derive(
91+ deepseek_v4_flash(
92+ num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path
93+ ),
94+ Trainer.Config,
95+ ),
85 GraphTrainerDeepSeekV4Model.Config,96 GraphTrainerDeepSeekV4Model.Config,
86 )97 )
87 config.compile = _graph_trainer_compile_config()98 config.compile = _graph_trainer_compile_config()
@@ -96,8 +107,11 @@ def graph_trainer_deepseek_v4_flash_43layers_16experts(
96) -> GraphTrainer.Config:107) -> GraphTrainer.Config:
97 """GraphTrainer config for the DeepSeek V4 Flash 43 Layers 16 experts model"""108 """GraphTrainer config for the DeepSeek V4 Flash 43 Layers 16 experts model"""
98 config = to_graph_trainer_config(109 config = to_graph_trainer_config(
99- deepseek_v4_flash_43layers_16experts(110+ derive(
100- num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path111+ deepseek_v4_flash_43layers_16experts(
112+ num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path
113+ ),
114+ Trainer.Config,
101 ),115 ),
102 GraphTrainerDeepSeekV4Model.Config,116 GraphTrainerDeepSeekV4Model.Config,
103 )117 )
@@ -113,7 +127,10 @@ def graph_trainer_deepseek_v4_pro(
113) -> GraphTrainer.Config:127) -> GraphTrainer.Config:
114 """GraphTrainer config for the DeepSeek V4 Pro model"""128 """GraphTrainer config for the DeepSeek V4 Pro model"""
115 config = to_graph_trainer_config(129 config = to_graph_trainer_config(
116- deepseek_v4_pro(num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path),130+ derive(
131+ deepseek_v4_pro(num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path),
132+ Trainer.Config,
133+ ),
117 GraphTrainerDeepSeekV4Model.Config,134 GraphTrainerDeepSeekV4Model.Config,
118 )135 )
119 config.compile = _graph_trainer_compile_config()136 config.compile = _graph_trainer_compile_config()
@@ -128,8 +145,11 @@ def graph_trainer_deepseek_v4_pro_61layers_32experts(
128) -> GraphTrainer.Config:145) -> GraphTrainer.Config:
129 """GraphTrainer config for the DeepSeek V4 Pro 61 Layers 32 experts model"""146 """GraphTrainer config for the DeepSeek V4 Pro 61 Layers 32 experts model"""
130 config = to_graph_trainer_config(147 config = to_graph_trainer_config(
131- deepseek_v4_pro_61layers_32experts(148+ derive(
132- num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path149+ deepseek_v4_pro_61layers_32experts(
150+ num_mtp_layers=0, parallelism=parallelism, seq_len=seq_len, hf_assets_path=hf_assets_path
151+ ),
152+ Trainer.Config,
133 ),153 ),
134 GraphTrainerDeepSeekV4Model.Config,154 GraphTrainerDeepSeekV4Model.Config,
135 )155 )