已合并
[refactor] 统一 DeepSeek-V4 主干与 MTP 参数精度策略 #1290
[refactor] 统一 DeepSeek-V4 主干与 MTP 参数精度策略 #1290
已合并
hanboyou创建于 20 天前
共 13 个文件变更+465-264
@@ -33,6 +33,9 @@
33 ".torchtitan.eager_flex",33 ".torchtitan.eager_flex",
34 ".compile.dynamo_config"34 ".compile.dynamo_config"
35 ],35 ],
36+ "torchtitan_npu/patches/torchtitan/distributed/__init__.py": [
37+ ".fsdp"
38+ ],
36 "torchtitan_npu/patches/torchtitan/__init__.py": [39 "torchtitan_npu/patches/torchtitan/__init__.py": [
37 ".components.metrics",40 ".components.metrics",
38 ".components.optimizer",41 ".components.optimizer",
@@ -10,6 +10,14 @@ 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 层。FP32 主参数搭配 BF16 默认计算时,这些参数仍以 FP32 参与计算,其他参数按 BF16 计算;主参数存储与 `reduce_dtype` 保持训练配置指定的值。
16+ 
17+共享策略使用参数自身 dtype 与 `param_dtype` 中较宽的类型。DeepSeek-V4 继续拒绝受保护参数自身和默认计算 dtype 均为 BF16 的组合,保持 TorchTitan 0.4.0 原有 FP32 override 请求的拒绝边界;该清理不新增这一训练模式。
18+ 
19+TorchTitan 0.4.0 通过包导入时安装的共享策略读取模块运行期声明,模型继承上游 FSDP/MTP 流程。该适配回移上游 [#5774](https://github.com/pytorch/torchtitan/pull/5774) 的精度策略机制,保留既有 Config 类型,不新增配置参数,也不改变 GraphTrainer SimpleFSDP、checkpoint 导出或 RL 权重传输。具体加载边界见[架构说明](../architecture.md#两阶段时序语义)。
20+ 
13## 当前支持的数据格式21## 当前支持的数据格式
14 22 
15当前实现中的量化数据和 scale 表示如下。不同量化路径分别使用低精度计算或 fake quant,并通过对应的反向实现传递梯度。23当前实现中的量化数据和 scale 表示如下。不同量化路径分别使用低精度计算或 fake quant,并通过对应的反向实现传递梯度。
@@ -6,19 +6,24 @@
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
16from torchtitan.models.deepseek_v4.mhc import HcPre21from torchtitan.models.deepseek_v4.mhc import HcPre
17 22 
18-from torchtitan_npu.models.common.fsdp import apply_fsdp_to_mtp_decoder, make_param_dtype_override_fn23+from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4Model
19 24 
20 25 
21-class _ProjectionBlock(nn.Module):26+class _ProjectionBlock(Module):
22 """Use actual V4 mixing and Linear modules in the decoder sharding layout."""27 """Use actual V4 mixing and Linear modules in the decoder sharding layout."""
23 28 
24 def __init__(self):29 def __init__(self):
@@ -31,11 +36,11 @@ class _ProjectionBlock(nn.Module):
31 return self.feed_forward(reduced), post, comb36 return self.feed_forward(reduced), post, comb
32 37 
33 38 
34-class _MTPDecoderLayout(nn.Module):39+class _MTPDecoderLayout(DeepSeekV4Model):
35- """The layer/MTP containers consumed by the production sharding bridge."""40+ """Small layer/MTP composition consumed by the upstream FSDP entry points."""
36 41 
37 def __init__(self):42 def __init__(self):
38- super().__init__()43+ Module.__init__(self)
39 self.enable_weight_tying = False44 self.enable_weight_tying = False
40 self.tok_embeddings = self.norm = self.lm_head = None45 self.tok_embeddings = self.norm = self.lm_head = None
41 self.layers = nn.ModuleDict({"0": _ProjectionBlock()})46 self.layers = nn.ModuleDict({"0": _ProjectionBlock()})
@@ -55,7 +60,18 @@ def cpu_mesh(tmp_path):
55 dist.destroy_process_group()60 dist.destroy_process_group()
56 61 
57 62 
58-def test_native_callback_preserves_fp32_model_and_mtp_weights_and_gradients(cpu_mesh):63+def test_shared_fsdp_policy_accepts_declared_bf16_parameters():
64+ with torch.random.fork_rng(devices=[]):
65+ model = _ProjectionBlock().bfloat16()
66+ 
67+ policy = fsdp.mixed_precision_policy(model, param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
68+ resolved = policy._resolve_for_param(model.hc_attn_pre.hc_fn)
69+ 
70+ assert resolved.param_dtype is torch.bfloat16
71+ 
72+ 
73+@pytest.mark.parametrize("entrypoint", ("v4-model", "explicit-callback"))
74+def test_upstream_fsdp_preserves_declared_model_and_mtp_weights_and_gradients(cpu_mesh, entrypoint):
59 with torch.random.fork_rng(devices=[]):75 with torch.random.fork_rng(devices=[]):
60 model = _MTPDecoderLayout()76 model = _MTPDecoderLayout()
61 with torch.no_grad():77 with torch.no_grad():
@@ -66,19 +82,43 @@ 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()}82 masters = {name: parameter.detach().clone() for name, parameter in model.named_parameters()}
67 for block in (reference.layers["0"], reference.mtp_layers[0]):83 for block in (reference.layers["0"], reference.mtp_layers[0]):
68 block.feed_forward.to(dtype=torch.bfloat16)84 block.feed_forward.to(dtype=torch.bfloat16)
69- overrides = {name: torch.float32 for name in masters if ".hc_attn_pre." in name}85+ overrides = (
70- callback = make_param_dtype_override_fn(model, overrides)86+ {}
87+ if entrypoint == "explicit-callback"
88+ else {name: torch.float32 for name in masters if ".hc_attn_pre." in name}
89+ )
90+ if entrypoint == "explicit-callback":
91+ reference.bfloat16()
71 original_layers = tuple(model.layers)92 original_layers = tuple(model.layers)
72 93 
73- apply_fsdp_to_mtp_decoder(94+ if entrypoint == "explicit-callback":
74- model,95+ alias = str(len(model.layers))
75- cpu_mesh,96+ model.layers[alias] = model.mtp_layers[0]
76- param_dtype=torch.bfloat16,97+ try:
77- reduce_dtype=torch.float32,98+ fsdp.apply_fsdp_to_decoder(
78- pp_enabled=False,99+ model,
79- reshard_after_forward_policy="never",100+ cpu_mesh,
80- param_dtype_override_fn=callback,101+ param_dtype=torch.bfloat16,
81- )102+ reduce_dtype=torch.float32,
103+ pp_enabled=False,
104+ reshard_after_forward_policy="never",
105+ param_dtype_override_fn=lambda _parameter: None,
106+ )
107+ finally:
108+ del model.layers[alias]
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+ DeepSeekV4Model._apply_fsdp(
117+ model,
118+ parallelism_context=context,
119+ training=TrainingConfig(mixed_precision_param="bfloat16", mixed_precision_reduce="float32"),
120+ parallelism=ParallelismConfig(fsdp_reshard_after_forward="never"),
121+ )
82 122 
83 assert tuple(model.layers) == original_layers123 assert tuple(model.layers) == original_layers
84 observed = {}124 observed = {}
@@ -3,28 +3,48 @@
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
16+from types import SimpleNamespace
15 17 
16import pytest18import pytest
17import torch19import torch
20+import torch.distributed as dist
21+import torchtitan.distributed.fsdp as fsdp
22+from torch import nn
18from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper23from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
19-from torchtitan.config import TrainingConfig24+from torch.distributed.device_mesh import init_device_mesh
25+from torch.distributed.fsdp import FSDPModule, MixedPrecisionPolicy
26+from torchtitan.config import TrainingConfig, derive
27+from torchtitan.config.parallelism import ParallelismConfig
28+from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router
29+from torchtitan.tools.utils import set_default_dtype
20 30 
21from tests.unit_tests.models.mtp_test_utils import SEQ_LEN, VOCAB_SIZE, build_cpu_model31from 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_config32from torchtitan_npu.models.deepseek_v4 import _make_v4_config
24-from torchtitan_npu.models.deepseek_v4.parallelize import _dsv4_param_dtypes
25 33 
26 34 
27-def _build_policy_model():35+class _RouterWithAdapter(DeepSeekV4Router):
36+ """Router owner containing a foreign adapter before model construction ends."""
37+ 
38+ @dataclass(kw_only=True, slots=True)
39+ class Config(DeepSeekV4Router.Config):
40+ pass
41+ 
42+ def __init__(self, config):
43+ super().__init__(config)
44+ self.adapter = nn.Linear(config.gate.in_features, config.num_experts, bias=True)
45+ 
46+ 
47+def _build_policy_model(*, router_adapter=False, master_dtype=torch.float32):
28 """Construct main HCA/CSA blocks and a dense MTP block through the factory."""48 """Construct main HCA/CSA blocks and a dense MTP block through the factory."""
29 config = _make_v4_config(49 config = _make_v4_config(
30 dim=32,50 dim=32,
@@ -58,124 +78,167 @@ def _build_policy_model():
58 original_seq_len=65536,78 original_seq_len=65536,
59 num_mtp_layers=1,79 num_mtp_layers=1,
60 )80 )
61- with torch.random.fork_rng(devices=[]):81+ if router_adapter:
82+ for layer in (*config.layers, *config.mtp_layers):
83+ layer.feed_forward.router = derive(layer.feed_forward.router, _RouterWithAdapter.Config)
84+ with torch.random.fork_rng(devices=[]), set_default_dtype(master_dtype):
62 return build_cpu_model(config)85 return build_cpu_model(config)
63 86 
64 87 
65-# Internal parameter family -> corresponding released-checkpoint family.88+@pytest.fixture
89+def cpu_mesh(tmp_path):
90+ assert not dist.is_initialized()
91+ dist.init_process_group("gloo", init_method=f"file://{tmp_path / 'store'}", rank=0, world_size=1)
92+ try:
93+ yield init_device_mesh("cpu", (1,), mesh_dim_names=("dp_shard",))
94+ finally:
95+ dist.destroy_process_group()
96+ 
97+ 
98+# Protected parameter families from the released checkpoint and training-router policy.
66# Checkpoint: deepseek-ai/DeepSeek-V4-Flash-0731, revision 7872f01b.99# Checkpoint: deepseek-ai/DeepSeek-V4-Flash-0731, revision 7872f01b.
67# hc_*, ape and attn_sink are F32; the checkpoint gate weight is BF16,100# hc_*, ape and attn_sink are F32; the checkpoint gate weight is BF16,
68# while training deliberately keeps the router gate in FP32.101# while training deliberately keeps the router gate in FP32.
69-FP32_PARAMETERS = {102+# The 48-shard audit found 433 F32 tensors. Gate bias is the expert_bias_E
70- "layers.*.hc_attn_pre.*": "layers.*.hc_attn_*",103+# buffer, so it is outside the parameter preservation policy.
71- "layers.*.hc_ffn_pre.*": "layers.*.hc_ffn_*",104+FP32_PARAMETERS = (
72- "layers.*.feed_forward.router.gate.weight": "layers.*.ffn.gate.weight",105+ "layers.*.hc_attn_pre.*",
73- "mtp_layers.*.hc_attn_pre.*": "mtp.*.hc_attn_*",106+ "layers.*.hc_ffn_pre.*",
74- "mtp_layers.*.hc_ffn_pre.*": "mtp.*.hc_ffn_*",107+ "layers.*.feed_forward.router.gate.weight",
75- "mtp_layers.*.feed_forward.router.gate.weight": "mtp.*.ffn.gate.weight",108+ "mtp_layers.*.hc_attn_pre.*",
76- "mtp_layers.*.hc_head.*": "mtp.*.hc_head_*",109+ "mtp_layers.*.hc_ffn_pre.*",
77- "hc_head.*": "hc_head_*",110+ "mtp_layers.*.feed_forward.router.gate.weight",
78- "layers.*.attention.compressor.ape": "layers.*.attn.compressor.ape",111+ "mtp_layers.*.hc_head.*",
79- "layers.*.attention.compressor_128.ape": "layers.*.attn.compressor.ape",112+ "hc_head.*",
80- "layers.*.attention.indexer.compressor.ape": "layers.*.attn.indexer.compressor.ape",113+ "layers.*.attention.compressor.ape",
81- "layers.*.attention.attn_sink.weight": "layers.*.attn.attn_sink",114+ "layers.*.attention.compressor_128.ape",
82- "mtp_layers.*.attention.attn_sink.weight": "mtp.*.attn.attn_sink",115+ "layers.*.attention.indexer.compressor.ape",
83-}116+ "layers.*.attention.attn_sink.weight",
84-# Independent audit of all 48 release shards: 72,317 tensors, 433 F32.117+ "mtp_layers.*.attention.attn_sink.weight",
85-HF_F32 = (
86- "layers.*.attn.attn_sink",
87- "layers.*.attn.compressor.ape",
88- "layers.*.attn.indexer.compressor.ape",
89- "layers.*.ffn.gate.bias",
90- "layers.*.hc_attn_*",
91- "layers.*.hc_ffn_*",
92- "mtp.*.attn.attn_sink",
93- "mtp.*.ffn.gate.bias",
94- "mtp.*.hc_attn_*",
95- "mtp.*.hc_ffn_*",
96- "mtp.*.hc_head_*",
97- "hc_head_*",
98)118)
99-# Checkpoint gate.bias is the FP32 feed_forward.expert_bias_E buffer.
100-HF_F32_BUFFERS = ("layers.*.ffn.gate.bias", "mtp.*.ffn.gate.bias")
101 119 
102 120 
103-def test_native_v4_fp32_parameter_families_are_selected_exactly():121+def test_v4_declares_the_expected_fp32_parameter_families():
104 model = _build_policy_model()122 model = _build_policy_model()
123+ patterns = FP32_PARAMETERS
105 names = tuple(name for name, _ in model.named_parameters())124 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)]125+ 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}"126 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)}127+ expected = {name for name in names if any(fnmatch.fnmatchcase(name, pattern) for pattern in patterns)}
109 128 
110- dtypes = _dsv4_param_dtypes(model, TrainingConfig())129+ declared = dict(model.named_preserve_dtype_params())
111 130 
112- assert set(dtypes) == expected131+ assert set(declared) == expected
113- assert set(dtypes.values()) == {torch.float32}132+ assert {parameter.dtype for parameter in declared.values()} == {torch.float32}
114- assert "layers.0.attention.compressor_128.ape" in dtypes133+ assert "layers.0.attention.compressor_128.ape" in declared
115- assert "layers.2.attention.compressor.ape" in dtypes134+ assert "layers.2.attention.compressor.ape" in declared
116- assert "layers.2.attention.indexer.compressor.ape" in dtypes135+ assert "layers.2.attention.indexer.compressor.ape" in declared
117- assert "mtp_layers.0.attention.attn_sink.weight" in dtypes136+ 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"):137 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 dtypes138+ assert name in names and name not in declared
120 139 
121 140 
122-def test_every_f32_tensor_of_the_release_is_covered():141+def test_model_declares_foreign_router_adapter_parameters_before_fsdp():
123- missing = [142+ model = _build_policy_model(router_adapter=True)
124- family143+ declared = dict(model.named_preserve_dtype_params())
125- for family in HF_F32144+ callback = fsdp.mixed_precision_policy(
126- if not any(fnmatch.fnmatchcase(family, hf) for hf in FP32_PARAMETERS.values())145+ model, param_dtype=torch.bfloat16, reduce_dtype=torch.float32
127- and not any(fnmatch.fnmatchcase(family, buffer) for buffer in HF_F32_BUFFERS)146+ ).param_dtype_override_fn
128- ]147+ assert callback is not None
129- assert not missing, f"Released F32 families missing from the training contract: {missing}"148+ 
149+ for prefix, layer in (
150+ *((f"layers.{index}", layer) for index, layer in model.layers.items()),
151+ *((f"mtp_layers.{index}", layer) for index, layer in enumerate(model.mtp_layers)),
152+ ):
153+ adapter = layer.feed_forward.router.adapter
154+ assert type(adapter) is nn.Linear
155+ for suffix in ("weight", "bias"):
156+ parameter = getattr(adapter, suffix)
157+ assert declared[f"{prefix}.feed_forward.router.adapter.{suffix}"] is parameter
158+ assert callback(parameter) is torch.float32
159+ assert callback(layer.feed_forward.routed_experts.w13.weight) is None
130 160 
131 161 
132-@pytest.mark.parametrize("reduce_dtype", ("float32", "bfloat16"))162+@pytest.mark.parametrize("compute_dtype", ("bfloat16", "float32"), ids=("bf16-compute", "fp32-compute"))
133-def test_native_callback_only_changes_selected_parameter_compute_dtype(reduce_dtype):163+@pytest.mark.parametrize("master_dtype", (torch.float32, torch.bfloat16), ids=("fp32-masters", "bf16-masters"))
134- model = _build_policy_model()164+def test_v4_fsdp_keeps_released_precision_support_boundary_and_parameter_storage(cpu_mesh, master_dtype, compute_dtype):
135- training = TrainingConfig(mixed_precision_param="bfloat16", mixed_precision_reduce=reduce_dtype)165+ model = _build_policy_model(master_dtype=master_dtype)
136- dtypes = _dsv4_param_dtypes(model, training)166+ reduce_dtype = "float32" if compute_dtype == "bfloat16" else "bfloat16"
137- callback = make_param_dtype_override_fn(model, dtypes)
138- 
139- for name, parameter in model.named_parameters():
140- expected = torch.float32 if any(fnmatch.fnmatchcase(name, pattern) for pattern in FP32_PARAMETERS) else None
141- assert callback(parameter) is expected, name
142- 
143- 
144-@pytest.mark.parametrize("scope", ("main-attention", "main-block", "mtp-block"))
145-def test_native_dtype_selection_survives_checkpoint_wrapping(scope):
146- plain_dtypes = _dsv4_param_dtypes(_build_policy_model(), TrainingConfig())
147- model = _build_policy_model()
148- if scope == "main-attention":
149- model.layers["0"].attention = checkpoint_wrapper(model.layers["0"].attention)
150- elif scope == "main-block":
151- model.layers["0"] = checkpoint_wrapper(model.layers["0"])
152- else:
153- model.mtp_layers[0] = checkpoint_wrapper(model.mtp_layers[0])
154- 
155- dtypes = _dsv4_param_dtypes(model, TrainingConfig())
156- assert any("_checkpoint_wrapped_module" in name for name in dtypes)
157- canonical = {
158- ".".join(part for part in name.split(".") if part != "_checkpoint_wrapped_module"): dtype
159- for name, dtype in dtypes.items()
160- }
161- assert canonical == plain_dtypes
162- callback = make_param_dtype_override_fn(model, dtypes)
163- for name, parameter in model.named_parameters():
164- assert callback(parameter) is dtypes.get(name), name
165- 
166- 
167-def test_native_callback_preserves_policy_through_temporary_mtp_layer_aliases():
168- model = _build_policy_model()
169 original_layers = tuple(model.layers)167 original_layers = tuple(model.layers)
170- dtypes = _dsv4_param_dtypes(model, TrainingConfig())168+ original_parameters = dict(model.named_parameters())
171- callback = make_param_dtype_override_fn(model, dtypes)169+ original_values = {name: parameter.detach().clone() for name, parameter in original_parameters.items()}
172- key = str(len(model.layers))170+ protected = {
173- model.layers[key] = model.mtp_layers[0]171+ id(parameter)
174- try:172+ for name, parameter in original_parameters.items()
175- aliased_parameters = dict(model.named_parameters(remove_duplicate=False))173+ if any(fnmatch.fnmatchcase(name, pattern) for pattern in FP32_PARAMETERS)
176- for suffix, parameter in model.mtp_layers[0].named_parameters():174+ }
177- assert aliased_parameters[f"layers.{key}.{suffix}"] is parameter175+ # Independent oracle: the released V4 policy selected FP32 unconditionally.
178- assert callback(parameter) is dtypes.get(f"mtp_layers.0.{suffix}"), suffix176+ released_policy = MixedPrecisionPolicy(
179- finally:177+ param_dtype=getattr(torch, compute_dtype),
180- del model.layers[key]178+ reduce_dtype=getattr(torch, reduce_dtype),
179+ cast_forward_inputs=False,
180+ param_dtype_override_fn=lambda parameter: torch.float32 if id(parameter) in protected else None,
181+ )
182+ context = SimpleNamespace(
183+ get_activated_mesh=lambda _axes: cpu_mesh,
184+ ep_enabled=False,
185+ pp_enabled=False,
186+ ep=1,
187+ )
188+ training = TrainingConfig(mixed_precision_param=compute_dtype, mixed_precision_reduce=reduce_dtype)
189+ parallelism = ParallelismConfig(fsdp_reshard_after_forward="never")
190+ 
191+ if master_dtype is torch.bfloat16 and compute_dtype == "bfloat16":
192+ parameter = next(p for p in original_parameters.values() if id(p) in protected and p.dtype is torch.bfloat16)
193+ with pytest.raises(ValueError, match="original dtype"):
194+ released_policy._resolve_for_param(parameter)
195+ with pytest.raises(ValueError, match="requires FP32 storage for protected parameter"):
196+ model._apply_fsdp(parallelism_context=context, training=training, parallelism=parallelism)
197+ assert not any(isinstance(module, FSDPModule) for module in model.modules())
198+ for name, parameter in model.named_parameters():
199+ torch.testing.assert_close(parameter, original_values[name], rtol=0, atol=0)
200+ return
201+ 
202+ expected = {name: released_policy._resolve_for_param(parameter) for name, parameter in original_parameters.items()}
203+ model._apply_fsdp(parallelism_context=context, training=training, parallelism=parallelism)
204+ 
181 assert tuple(model.layers) == original_layers205 assert tuple(model.layers) == original_layers
206+ names_by_id = {id(parameter): name for name, parameter in model.named_parameters()}
207+ observed = {}
208+ for module in model.modules():
209+ if not isinstance(module, FSDPModule):
210+ continue
211+ group = module._get_fsdp_state()._fsdp_param_group
212+ if group is None:
213+ continue
214+ for parameter in group.fsdp_params:
215+ name = names_by_id[id(parameter.sharded_param)]
216+ actual = parameter.mp_policy
217+ observed[name] = actual.param_dtype
218+ assert actual.param_dtype is expected[name].param_dtype, name
219+ assert actual.reduce_dtype is getattr(torch, reduce_dtype)
220+ assert actual.cast_forward_inputs is False
221+ torch.testing.assert_close(parameter.sharded_param.to_local(), original_values[name], rtol=0, atol=0)
222+ assert observed.keys() == original_parameters.keys()
223+ 
224+ 
225+def test_declared_dtype_selection_survives_checkpoint_wrapping():
226+ plain_names = set(dict(_build_policy_model().named_preserve_dtype_params()))
227+ model = _build_policy_model()
228+ model.layers["0"] = checkpoint_wrapper(model.layers["0"])
229+ model.mtp_layers[0] = checkpoint_wrapper(model.mtp_layers[0])
230+ 
231+ declared = dict(model.named_preserve_dtype_params())
232+ assert any("_checkpoint_wrapped_module" in name for name in declared)
233+ canonical = {
234+ ".".join(part for part in name.split(".") if part != "_checkpoint_wrapped_module")
235+ for name in declared
236+ }
237+ assert canonical == plain_names
238+ callback = fsdp.mixed_precision_policy(
239+ model, param_dtype=torch.bfloat16, reduce_dtype=torch.float32
240+ ).param_dtype_override_fn
241+ assert callback is not None
242+ for name, parameter in model.named_parameters():
243+ expected = torch.float32 if name in declared else None
244+ assert callback(parameter) is expected, name
@@ -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]
@@ -8,15 +8,17 @@ 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, TrainingConfig11+from torchtitan.models.base.module import Module
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_nparams12from torchtitan.models.common.flops import get_nparams_and_active_nparams
15from torchtitan.models.deepseek_v4.model import DeepSeekV4TransformerBlock as DeepSeekV4TransformerBlock13from torchtitan.models.deepseek_v4.model import DeepSeekV4TransformerBlock as DeepSeekV4TransformerBlock
16 14 
17from .mtp import DeepSeekV4MTPDecoder15from .mtp import DeepSeekV4MTPDecoder
18 16 
19if TYPE_CHECKING:17if TYPE_CHECKING:
18+ from torchtitan.config import TrainingConfig
19+ from torchtitan.config.parallelism import ParallelismConfig
20+ from torchtitan.distributed.parallelism_context import ParallelismContext
21+ 
20 from .compressor import Indexer22 from .compressor import Indexer
21 from .mtp import DeepSeekV4MTPTransformerBlock23 from .mtp import DeepSeekV4MTPTransformerBlock
22 24 
@@ -54,35 +56,24 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder):
54 def _apply_fsdp(56 def _apply_fsdp(
55 self,57 self,
56 *,58 *,
57- parallelism_context: ParallelismContext,59+ parallelism_context: "ParallelismContext",
58- training: TrainingConfig,60+ training: "TrainingConfig",
59- parallelism: ParallelismConfig,61+ parallelism: "ParallelismConfig",
60 ) -> None:62 ) -> None:
61- from torchtitan.distributed.fsdp import resolve_fsdp_mesh, resolve_sparse_fsdp_mesh63+ # The released FP32 override rejected BF16 storage with a BF16 policy.
62- 64+ # Preserving that rejection avoids silently enabling a different policy.
63- from torchtitan_npu.models.common.fsdp import apply_fsdp_to_mtp_decoder, make_param_dtype_override_fn65+ if training.mixed_precision_param == "bfloat16":
64- 66+ for name, parameter in Module.named_preserve_dtype_params(self): # pyrefly: ignore [missing-attribute]
65- dp_mesh, dp_mesh_dims = resolve_fsdp_mesh(parallelism_context)67+ if parameter.dtype is not torch.float32:
66- edp_mesh, edp_mesh_dims = resolve_sparse_fsdp_mesh(parallelism_context)68+ raise ValueError(
67- 69+ f"DeepSeek-V4 requires FP32 storage for protected parameter {name!r} "
68- from .parallelize import _dsv4_param_dtypes70+ f"with mixed_precision_param='bfloat16', got {parameter.dtype}. "
69- 71+ "Use FP32 master parameters or mixed_precision_param='float32'."
70- apply_fsdp_to_mtp_decoder(72+ )
71- # The helper requires the decoder/layers/MTP structure, shared by73+ super()._apply_fsdp(
72- # this implementation and the upstream DeepSeek V4 model.74+ parallelism_context=parallelism_context,
73- self,75+ training=training,
74- dp_mesh,76+ parallelism=parallelism,
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 )77 )
87 78 
88 @dataclass(kw_only=True, slots=True)79 @dataclass(kw_only=True, slots=True)
@@ -132,6 +123,20 @@ class DeepSeekV4Model(DeepSeekV4MTPDecoder):
132 123 
133 def __init__(self, config: Config):124 def __init__(self, config: Config):
134 super().__init__(config)125 super().__init__(config)
126+ mtp_layers = cast("nn.ModuleList | None", self.mtp_layers)
127+ for layer in (*self.layers.values(), *(mtp_layers if mtp_layers is not None else ())):
128+ # The training router policy also covers adapter/quantization children.
129+ router = cast("nn.Module | None", getattr(layer.feed_forward, "router", None))
130+ if router is not None:
131+ for module in router.modules():
132+ names = tuple(name for name, parameter in module._parameters.items() if parameter is not None)
133+ setattr(module, "_preserve_dtype_params", names) # noqa: B010 -- API backported on existing modules
134+ attention = cast("nn.Module", layer.attention)
135+ sink = cast("nn.Module | nn.Parameter", attention.attn_sink)
136+ if isinstance(sink, nn.Parameter):
137+ setattr(attention, "_preserve_dtype_params", ("attn_sink",)) # noqa: B010
138+ else:
139+ setattr(sink, "_preserve_dtype_params", ("weight",)) # noqa: B010
135 140 
136 141 
137class GraphTrainerDeepSeekV4Model(DeepSeekV4Model):142class GraphTrainerDeepSeekV4Model(DeepSeekV4Model):
@@ -29,61 +29,10 @@ if TYPE_CHECKING:
29 from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig29 from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig
30 30 
31 from torchtitan_npu.models.deepseek_v4.model import (31 from torchtitan_npu.models.deepseek_v4.model import (
32- DeepSeekV4Model,
33 GraphTrainerDeepSeekV4Model,32 GraphTrainerDeepSeekV4Model,
34 )33 )
35 34 
36 35 
37-def _dsv4_param_dtypes(
38- model: DeepSeekV4Model,
39- training: TrainingConfig,
40-) -> dict[str, torch.dtype]:
41- """Return the fqn-fp32 policy map for DSV4 SmoE hyper-connection and MoE router parameters."""
42- 
43- def matches_any(fqn: str, patterns: tuple[str, ...]) -> bool:
44- """Check if a module/parameter FQN matches any of the fnmatch patterns."""
45- clean = ".".join(part for part in fqn.split(".") if part != "_checkpoint_wrapped_module")
46- return any(matches_module_fqn_pattern(pattern, clean) for pattern in patterns)
47- 
48- fp32_module_fqns = (
49- "layers.*.hc_attn_pre",
50- "layers.*.hc_ffn_pre",
51- "layers.*.feed_forward.router",
52- "layers.*.hc_head",
53- "mtp_layers.*.hc_attn_pre",
54- "mtp_layers.*.hc_ffn_pre",
55- "mtp_layers.*.feed_forward.router",
56- "mtp_layers.*.hc_head",
57- "hc_head",
58- )
59- fp32_parameter_fqns = (
60- "layers.*.attention.compressor.ape",
61- "layers.*.attention.compressor_128.ape",
62- "layers.*.attention.compressor_128.ape",
63- "layers.*.attention.indexer.compressor.ape",
64- "mtp_layers.*.attention.compressor.ape",
65- "mtp_layers.*.attention.compressor_128.ape",
66- "mtp_layers.*.attention.compressor_128.ape",
67- "mtp_layers.*.attention.indexer.compressor.ape",
68- # Learned per-head softmax logits: created FP32 in attention.py and
69- # required FP32 by the attention kernels.
70- "layers.*.attention.attn_sink",
71- "layers.*.attention.attn_sink.weight",
72- "mtp_layers.*.attention.attn_sink",
73- "mtp_layers.*.attention.attn_sink.weight",
74- )
75- 
76- fp32_modules = [module for name, module in model.named_modules() if matches_any(name, fp32_module_fqns)]
77- fp32_param_ids = {id(param) for module in fp32_modules for param in module.parameters()}
78- 
79- overrides: dict[str, torch.dtype] = {}
80- for name, parameter in model.named_parameters(remove_duplicate=False):
81- if id(parameter) in fp32_param_ids or matches_any(name, fp32_parameter_fqns):
82- overrides[name] = torch.float32
83- 
84- return overrides
85- 
86- 
87def parallelize_deepseek_v4(model, **kwargs):36def parallelize_deepseek_v4(model, **kwargs):
88 """Apply upstream eager parallelization with DSV4 FP32 parameter policies."""37 """Apply upstream eager parallelization with DSV4 FP32 parameter policies."""
89 from torchtitan.models.base.model import BaseModel38 from torchtitan.models.base.model import BaseModel
@@ -1 +1,9 @@
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+ 
1"""Patches for TorchTitan distributed utilities."""6"""Patches for TorchTitan distributed utilities."""
7+ 
8+from ..models import base # noqa: F401
9+from . import fsdp # noqa: F401
@@ -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+ )
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]
36+ "ape",
37+ )
38+ 
39+ 
40+apply()