Draft
[WIP][refactor] 复用上游 DeepSeek-V4 GraphTrainer 配置转换 #1287
[WIP][refactor] 复用上游 DeepSeek-V4 GraphTrainer 配置转换 #1287
Draft
hanboyouAdd on 20 days ago
Total: 6 files changed+70-64
@@ -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 
@@ -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)
@@ -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)
@@ -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 )