Open
[fix] Align v0.4.0 performance with v0.3.0 #1424
[fix] Align v0.4.0 performance with v0.3.0 #1424
Open
1Fire4Add on 6 days ago
Total: 17 files changed+391-120
@@ -0,0 +1,70 @@
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+import pytest
7+import torch
8+import torch.distributed as dist
9+from torch import nn
10+from torch.distributed.device_mesh import init_device_mesh
11+from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
12+from torch.nn import functional as F
13+from torchtitan.components.loss import CrossEntropyLoss
14+ 
15+from torchtitan_npu.models.common.chunked_loss import FP32HeadGradChunkedLoss
16+ 
17+ 
18+@pytest.mark.parametrize("num_chunks", [2, 4])
19+def test_chunked_fsdp_head_accumulates_bf16_gradients_in_fp32(tmp_path, num_chunks):
20+ dist.init_process_group("gloo", init_method=f"file://{tmp_path / 'store'}", rank=0, world_size=1)
21+ try:
22+ mesh = init_device_mesh("cpu", (1,))
23+ head = nn.Linear(4, 8, bias=False)
24+ weight = torch.linspace(-0.5, 0.5, head.weight.numel()).reshape_as(head.weight)
25+ with torch.no_grad():
26+ head.weight.copy_(weight)
27+ fully_shard(
28+ head, mesh=mesh, mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
29+ )
30+ pred = torch.linspace(-1, 1, 32).reshape(8, 4).to(torch.bfloat16).requires_grad_()
31+ labels = torch.tensor([0, 5, 2, 3, 7, 4, 5, 1])
32+ count = torch.tensor(labels.numel())
33+ with torch.no_grad():
34+ head(pred)
35+ group = head._get_fsdp_state()._fsdp_param_groups[0]
36+ if not hasattr(group, "_fsdp_params_with_wider_grad_dtype"):
37+ pytest.skip("FSDP runtime uses its own head gradient accumulation")
38+ param = group.fsdp_params[0]
39+ loss_fn = FP32HeadGradChunkedLoss.Config(
40+ num_chunks=num_chunks, loss_fn=CrossEntropyLoss.Config(global_vocab_size=8)
41+ ).build()
42+ loss_fn.set_lm_head(head)
43+ grad_dtypes = []
44+ handle = head.register_forward_hook(lambda *_: grad_dtypes.append(param.unsharded_param.grad_dtype))
45+ try:
46+ loss, _ = loss_fn(pred, labels, count)
47+ loss.backward()
48+ finally:
49+ handle.remove()
50+ 
51+ expected_loss = torch.zeros(())
52+ expected_grads = []
53+ expected_input_grads = []
54+ for inputs, targets in zip(pred.detach().chunk(num_chunks), labels.chunk(num_chunks), strict=True):
55+ inputs.requires_grad_()
56+ ref_weight = weight.bfloat16().requires_grad_()
57+ logits = F.linear(inputs, ref_weight).float()
58+ chunk_loss = F.cross_entropy(logits, targets, reduction="sum") / count
59+ input_grad, weight_grad = torch.autograd.grad(chunk_loss, (inputs, ref_weight))
60+ expected_loss += chunk_loss.detach()
61+ expected_grads.append(weight_grad.float())
62+ expected_input_grads.append(input_grad)
63+ 
64+ assert grad_dtypes == [None] * num_chunks
65+ assert param.unsharded_param.grad_dtype is torch.float32
66+ torch.testing.assert_close(loss, expected_loss, rtol=0, atol=0)
67+ torch.testing.assert_close(pred.grad, torch.cat(expected_input_grads), rtol=0, atol=0)
68+ torch.testing.assert_close(head.weight.grad.to_local(), sum(expected_grads), rtol=0, atol=0)
69+ finally:
70+ dist.destroy_process_group()
@@ -11,6 +11,7 @@ import importlib
11import pytest11import pytest
12import torch12import torch
13import torch.nn as nn13import torch.nn as nn
14+import torch_remat
14from torchtitan.components.data import GrainDataLoader15from torchtitan.components.data import GrainDataLoader
15from torchtitan.config.parallelism import ParallelismConfig16from torchtitan.config.parallelism import ParallelismConfig
16 17 
@@ -166,27 +167,6 @@ def parallelize_deps(monkeypatch):
166 return par, parallel_dims167 return par, parallel_dims
167 168 
168 169 
169-def _parallelize(par, parallel_dims, recipes, model, *, vision: bool):
170- trainer = (
171- recipes.deepseek_v4_1_debugmodel_multimodal()
172- if vision
173- else recipes._make_trainer_config("deepseek_v4_1_debugmodel_text")
174- )
175- # The dispatch under test is backend-independent; the recipe's spmd_types path routes
176- # through the sharding validation and the model's own parallelize instead, so this
177- # takes the plain FSDP backend.
178- parallelism = dataclasses.replace(trainer.parallelism, spmd_backend="partial_dtensor")
179- return par.parallelize_deepseek_v4_1(
180- model,
181- parallel_dims=parallel_dims,
182- training=trainer.training,
183- parallelism=parallelism,
184- compile_config=trainer.compile,
185- ac_config=trainer.activation_remat,
186- dump_folder=".",
187- )
188- 
189- 
190def test_parallelize_never_asks_the_text_stack_for_the_hooks(registry, recipes, parallelize_deps):170def test_parallelize_never_asks_the_text_stack_for_the_hooks(registry, recipes, parallelize_deps):
191 """A text run reaches both dispatch points without the hooks existing.171 """A text run reaches both dispatch points without the hooks existing.
192 172 
@@ -206,37 +186,41 @@ def test_parallelize_never_asks_the_text_stack_for_the_hooks(registry, recipes,
206 assert model.calls == []186 assert model.calls == []
207 187 
208 188 
209-def test_parallelize_asks_the_multimodal_stack_for_both_hooks(registry, recipes, parallelize_deps):189+def test_multimodal_parallelize_wraps_each_vision_block_before_fsdp(monkeypatch, recipes, single_rank_spmd):
210- """The multimodal branch reaches both hooks, which is the only reason they exist."""190+ trainer = recipes.deepseek_v4_1_debugmodel_multimodal()
211- par, parallel_dims = parallelize_deps191+ model = build_cpu_model(trainer.model)
212- model = build_cpu_model(registry.build_model_config("deepseek_v4_1_debugmodel"))192+ wrapped = {}
213- calls: list[str] = []193+ original_checkpoint = torch_remat.checkpoint
214- # The hooks are this class's own methods; recording them here keeps the assertion
215- # about dispatch, while ``test_multimodal_ac_hook_wraps_every_vision_block`` covers
216- # what the AC hook does with a real policy.
217- model.apply_activation_checkpointing_extensions = lambda policy: calls.append("ac")
218- model.apply_fsdp_extensions = lambda **kwargs: calls.append("fsdp")
219- _parallelize(par, parallel_dims, recipes, model, vision=True)
220- assert calls == ["ac", "fsdp"]
221 194 
195+ def record_checkpoint(*, region_name, **kwargs):
196+ checkpoint = original_checkpoint(region_name=region_name, **kwargs)
222 197 
223-def test_multimodal_ac_hook_wraps_every_vision_block(registry):198+ def wrap(forward):
224- """The AC hook is the tower's only route into the selected policy.199+ wrapped[region_name] = checkpoint(forward)
200+ return wrapped[region_name]
225 201 
226- The policy's own walk covers decoder layers; a vision block lives outside that list,202+ return wrap
227- so it is wrapped here or not at all.
228- """
229- config = registry.build_model_config("deepseek_v4_1_debugmodel")
230- model = build_cpu_model(config)
231- wrapped: list[str] = []
232 203 
233- class _Policy:204+ sharded = []
234- @staticmethod
235- def _wrap_block(block, *, base_fqn):
236- wrapped.append(base_fqn)
237- return block
238 205 
239- model.apply_activation_checkpointing_extensions(_Policy())206+ def check_vision_before_fsdp(**kwargs):
240- expected = [f"vision_encoder.blocks.{name}" for name, _ in model.vision_encoder.blocks.named_children()]207+ expected = {
241- assert wrapped == expected208+ f"vision_encoder.blocks.{name}": block.forward
242- assert len(wrapped) == 32209+ for name, block in model.vision_encoder.blocks.named_children()
210+ }
211+ assert len(expected) == 32
212+ assert all(wrapped.get(name) is forward for name, forward in expected.items())
213+ sharded.append(model)
214+ 
215+ monkeypatch.setattr(torch_remat, "checkpoint", record_checkpoint)
216+ monkeypatch.setattr(model, "_apply_fsdp", check_vision_before_fsdp)
217+ result = model.parallelize(
218+ parallelism_context=single_rank_spmd,
219+ training=trainer.training,
220+ parallelism=trainer.parallelism,
221+ local_compile_regions=[],
222+ activation_remat=trainer.activation_remat,
223+ dump_folder=".",
224+ )
225+ assert result is model
226+ assert sharded == [model]
@@ -93,6 +93,27 @@ def test_a5_eight_rank_multimodal_qat_recipe(example_environment):
93 assert "torchtitan_npu.override.deepseek_v4_1.mhc.asc_sinkhorn" not in config.override.imports93 assert "torchtitan_npu.override.deepseek_v4_1.mhc.asc_sinkhorn" not in config.override.imports
94 94 
95 95 
96+@pytest.mark.cpu
97+def test_compiled_a5_engram_projection_round_trips_hf_weight(example_environment):
98+ import torch
99+ 
100+ from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter
101+ 
102+ config = ConfigLoader().load([
103+ "--module", "torchtitan_npu_recipes.tests.models.deepseek_v4_1",
104+ "--config", "deepseek_v4_1_flash_8p_cpt_4k_a5_balanced_compile",
105+ ])
106+ adapter = DeepSeekV41StateDictAdapter(config.model, None)
107+ hf_key = "layers.1.engram.wkv.weight"
108+ native_key = "layers.1.engram.gate.wkv.weight"
109+ weight = torch.arange(8, dtype=torch.float32).reshape(2, 4)
110+ native = adapter.from_hf({hf_key: weight})
111+ torch.testing.assert_close(native[native_key], weight, rtol=0, atol=0)
112+ torch.testing.assert_close(adapter.to_hf(native)[hf_key], weight, rtol=0, atol=0)
113+ muon = next(group for group in config.optim.optimizer.optimizers if hasattr(group, "compute_sharding_by_fqn"))
114+ assert native_key in muon.compute_sharding_by_fqn
115+ 
116+ 
96@pytest.mark.cpu117@pytest.mark.cpu
97def test_long_context_recipe_uses_document_cp_and_full_recomputation():118def test_long_context_recipe_uses_document_cp_and_full_recomputation():
98 from torchtitan.distributed.activation_remat import FullActivationRematConfig119 from torchtitan.distributed.activation_remat import FullActivationRematConfig
@@ -216,7 +216,6 @@ class DeepSeekV4QuantLightningIndexerComponent(QuantComponent):
216 dst_type_max=ctx.dst_type_max,216 dst_type_max=ctx.dst_type_max,
217 ),217 ),
218 filters[V4FilterKeys.LIGHTNING_INDEXER],218 filters[V4FilterKeys.LIGHTNING_INDEXER],
219- model_compile_enabled=ctx.model_compile_enabled,
220 unified_npu_quant_modules=ctx.unified_npu_quant_modules,219 unified_npu_quant_modules=ctx.unified_npu_quant_modules,
221 specific_npu_quant_modules=ctx.specific_npu_quant_modules,220 specific_npu_quant_modules=ctx.specific_npu_quant_modules,
222 )221 )
@@ -271,7 +270,6 @@ class DeepSeekV4QuantSparseAttentionComponent(QuantComponent):
271 _quantization_converter(270 _quantization_converter(
272 None,271 None,
273 _v4_inner_attention_filter,272 _v4_inner_attention_filter,
274- model_compile_enabled=ctx.model_compile_enabled,
275 replacement_config_type=QuantizedV4SparseAttention.Config,273 replacement_config_type=QuantizedV4SparseAttention.Config,
276 replacement_kwargs={274 replacement_kwargs={
277 **geometry,275 **geometry,
@@ -71,7 +71,6 @@ class DeepSeekV41QuantLightningIndexerComponent(QuantComponent):
71 _quantization_converter(71 _quantization_converter(
72 DeepSeekV41QuantLightningIndexerConfig(),72 DeepSeekV41QuantLightningIndexerConfig(),
73 filters[V41FilterKeys.LIGHTNING_INDEXER],73 filters[V41FilterKeys.LIGHTNING_INDEXER],
74- model_compile_enabled=ctx.model_compile_enabled,
75 unified_npu_quant_modules=ctx.unified_npu_quant_modules,74 unified_npu_quant_modules=ctx.unified_npu_quant_modules,
76 specific_npu_quant_modules=ctx.specific_npu_quant_modules,75 specific_npu_quant_modules=ctx.specific_npu_quant_modules,
77 )76 )
@@ -115,7 +114,6 @@ class DeepSeekV41QuantCompressorComponent(QuantComponent):
115 _quantization_converter(114 _quantization_converter(
116 DeepSeekV41QuantCompressorConfig(),115 DeepSeekV41QuantCompressorConfig(),
117 filters[V41FilterKeys.COMPRESSOR],116 filters[V41FilterKeys.COMPRESSOR],
118- model_compile_enabled=ctx.model_compile_enabled,
119 unified_npu_quant_modules=ctx.unified_npu_quant_modules,117 unified_npu_quant_modules=ctx.unified_npu_quant_modules,
120 specific_npu_quant_modules=ctx.specific_npu_quant_modules,118 specific_npu_quant_modules=ctx.specific_npu_quant_modules,
121 )119 )
@@ -143,7 +141,6 @@ class DeepSeekV41QuantSparseAttentionComponent(QuantComponent):
143 _quantization_converter(141 _quantization_converter(
144 None,142 None,
145 filters[V41FilterKeys.SPARSE_ATTENTION],143 filters[V41FilterKeys.SPARSE_ATTENTION],
146- model_compile_enabled=ctx.model_compile_enabled,
147 replacement_config_type=QuantV41SparseAttention.Config,144 replacement_config_type=QuantV41SparseAttention.Config,
148 replacement_kwargs={145 replacement_kwargs={
149 **v41_geometry,146 **v41_geometry,
@@ -48,7 +48,7 @@ class V41FilterKeys:
48 48 
49 49 
50V41_FILTER_SPECS: dict[str, FilterSpec] = {50V41_FILTER_SPECS: dict[str, FilterSpec] = {
51- V41FilterKeys.DENSE: {"suffixes": _DENSE},51+ V41FilterKeys.DENSE: {"suffixes": (*_DENSE, ".engram.gate.wkv")},
52 V41FilterKeys.ROUTED_EXPERT: {"suffixes": _ROUTED},52 V41FilterKeys.ROUTED_EXPERT: {"suffixes": _ROUTED},
53 V41FilterKeys.LIGHTNING_INDEXER: {"suffixes": (".attention.indexer.inner_indexer",)},53 V41FilterKeys.LIGHTNING_INDEXER: {"suffixes": (".attention.indexer.inner_indexer",)},
54 V41FilterKeys.SPARSE_ATTENTION: {"suffixes": (".attention.inner_attention",)},54 V41FilterKeys.SPARSE_ATTENTION: {"suffixes": (".attention.inner_attention",)},
@@ -57,7 +57,7 @@ V41_FILTER_SPECS: dict[str, FilterSpec] = {
57V41_EXTRA_FILTERS = {V41FilterKeys.COMPRESSOR: _is_v41_kv_source}57V41_EXTRA_FILTERS = {V41FilterKeys.COMPRESSOR: _is_v41_kv_source}
58 58 
59V41_PREQUANTIZE_DEFAULT_FQNS: dict[str, tuple[str, ...]] = {59V41_PREQUANTIZE_DEFAULT_FQNS: dict[str, tuple[str, ...]] = {
60- V41FilterKeys.DENSE: _PREQUANTIZABLE_DENSE,60+ V41FilterKeys.DENSE: (*_PREQUANTIZABLE_DENSE, ".engram.gate.wkv"),
61 V41FilterKeys.ROUTED_EXPERT: _ROUTED,61 V41FilterKeys.ROUTED_EXPERT: _ROUTED,
62}62}
63 63 
@@ -121,7 +121,6 @@ def _quantization_converter(
121 base_config: AOBaseConfig | None,121 base_config: AOBaseConfig | None,
122 filter_fn: ConfigFilterFn | None = None,122 filter_fn: ConfigFilterFn | None = None,
123 *,123 *,
124- model_compile_enabled: bool,
125 replacement_config_type: type | None = None,124 replacement_config_type: type | None = None,
126 replacement_kwargs: dict[str, object] | None = None,125 replacement_kwargs: dict[str, object] | None = None,
127 prequantize_fqns: tuple[str, ...] | None = None,126 prequantize_fqns: tuple[str, ...] | None = None,
@@ -129,8 +128,6 @@ def _quantization_converter(
129 specific_npu_quant_modules: dict[type, type] | None = None,128 specific_npu_quant_modules: dict[type, type] | None = None,
130 recurse: bool = False,129 recurse: bool = False,
131) -> NpuQuantizeConverter.Config:130) -> NpuQuantizeConverter.Config:
132- if model_compile_enabled:
133- raise NotImplementedError("NPU quantization with model compilation is not supported in this upgrade")
134 return NpuQuantizeConverter.Config(131 return NpuQuantizeConverter.Config(
135 base_config=base_config,132 base_config=base_config,
136 filter_fn=filter_fn,133 filter_fn=filter_fn,
@@ -333,8 +330,16 @@ def _recipe_converters(
333 enable_hif8_save_quant_codes: bool = False,330 enable_hif8_save_quant_codes: bool = False,
334) -> list[QuantizationConverter.Config]:331) -> list[QuantizationConverter.Config]:
335 from .components import component_names_for_model, instantiate_component_for_model_and_name332 from .components import component_names_for_model, instantiate_component_for_model_and_name
336- from .configs import get_model_config333+ from .configs import ModelType, get_model_config
337 334 
335+ if model_compile_enabled and (
336+ model_type != ModelType.V4_1
337+ or recipe != "all_block_fp8"
338+ or enable_mxfp4_qat
339+ or li_quantization
340+ or enable_sparse_attention_quantization
341+ ):
342+ raise NotImplementedError("Block compilation with NPU quantization supports V4.1 block FP8")
338 model_quant_config = get_model_config(model_type)343 model_quant_config = get_model_config(model_type)
339 filters = model_quant_config.filters344 filters = model_quant_config.filters
340 if filters is None:345 if filters is None:
@@ -379,7 +384,6 @@ def _recipe_converters(
379 _quantization_converter(384 _quantization_converter(
380 param_swap_spec.swap_config,385 param_swap_spec.swap_config,
381 param_swap_spec.filter,386 param_swap_spec.filter,
382- model_compile_enabled=model_compile_enabled,
383 prequantize_fqns=_scope_fqns(param_swap_spec),387 prequantize_fqns=_scope_fqns(param_swap_spec),
384 unified_npu_quant_modules=model_quant_config.unified_npu_quant_modules,388 unified_npu_quant_modules=model_quant_config.unified_npu_quant_modules,
385 specific_npu_quant_modules=model_quant_config.specific_npu_quant_modules,389 specific_npu_quant_modules=model_quant_config.specific_npu_quant_modules,
@@ -240,7 +240,10 @@ class TrainerEx(Trainer):
240 quantization_config.recipe,240 quantization_config.recipe,
241 )241 )
242 # GraphTrainer's pass pipeline compiles the training step, not individual model regions.242 # GraphTrainer's pass pipeline compiles the training step, not individual model regions.
243- model_compile_enabled = getattr(config.compile, "model", None) is not None243+ model_compile_enabled = (
244+ getattr(config.compile, "model", None) is not None
245+ or getattr(config.model, "block_compile", None) is not None
246+ )
244 config.model = apply_quantization_converter(247 config.model = apply_quantization_converter(
245 config.model,248 config.model,
246 quantization_config,249 quantization_config,
@@ -0,0 +1,105 @@
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+"""FSDP mixed-precision gradient accumulation for chunked output heads."""
7+ 
8+from dataclasses import dataclass
9+from typing import TYPE_CHECKING, Any
10+ 
11+import torch
12+from torch import nn
13+from torch.distributed.fsdp import FSDPModule
14+from torchtitan.components.loss import ChunkedLossWrapper
15+ 
16+if TYPE_CHECKING:
17+ from torch.utils.hooks import RemovableHandle
18+ 
19+ 
20+class FP32HeadGradChunkedLoss(ChunkedLossWrapper):
21+ """Accumulate BF16 head gradients in FP32 outside the autograd leaf."""
22+ 
23+ @dataclass(kw_only=True, slots=True)
24+ class Config(ChunkedLossWrapper.Config):
25+ pass
26+ 
27+ def __call__(
28+ self,
29+ pred: torch.Tensor | tuple[torch.Tensor, ...],
30+ labels: torch.Tensor | tuple[torch.Tensor, ...],
31+ global_loss_token_counts: torch.Tensor | None = None,
32+ **loss_inputs: Any,
33+ ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
34+ head = self.lm_head
35+ if (
36+ not isinstance(head, FSDPModule)
37+ or self.num_chunks < 2
38+ or not torch.is_grad_enabled()
39+ or getattr(head, "inplace_wgrad_accum", False)
40+ ):
41+ return super().__call__(pred, labels, global_loss_token_counts, **loss_inputs)
42+ 
43+ # The pinned FSDP runtime exposes the wider-gradient policy after lazy init.
44+ # Runtimes with a separate FSDP accumulation buffer already take this path.
45+ groups = getattr(head._get_fsdp_state(), "_fsdp_param_groups", ())
46+ for group in groups:
47+ for param in getattr(group, "_fsdp_params_with_wider_grad_dtype", ()):
48+ if (
49+ param._module_info.module is head
50+ and param._module_info.param_name == "weight"
51+ and not param._module_info.shared_modules
52+ and param.sharded_param.requires_grad
53+ and param.param_dtype == torch.bfloat16
54+ and param.reduce_dtype == torch.float32
55+ ):
56+ return self._call_with_fp32_head_grad(
57+ head, group, param, pred, labels, global_loss_token_counts, **loss_inputs
58+ )
59+ return super().__call__(pred, labels, global_loss_token_counts, **loss_inputs)
60+ 
61+ def _call_with_fp32_head_grad(
62+ self, head: nn.Module, group, param, pred, labels, global_loss_token_counts, **loss_inputs
63+ ):
64+ accumulator: torch.Tensor | None = None
65+ leaf: nn.Parameter | None = None
66+ grad_hook: RemovableHandle | None = None
67+ 
68+ def accumulate(weight):
69+ nonlocal accumulator
70+ grad = weight.grad
71+ if accumulator is None:
72+ if group.reduce_grads:
73+ return
74+ accumulator = grad.to(torch.float32)
75+ else:
76+ accumulator.add_(grad)
77+ weight.grad = None
78+ if group.reduce_grads:
79+ # Hand the FP32 gradient to the native final-chunk ReduceScatter.
80+ weight.grad_dtype = torch.float32
81+ weight.grad = accumulator
82+ accumulator = None
83+ 
84+ def prepare_head_grad(_module, _args):
85+ nonlocal leaf, grad_hook
86+ if leaf is None:
87+ leaf = param.unsharded_param
88+ if leaf.grad is None:
89+ grad_hook = leaf.register_post_accumulate_grad_hook(accumulate)
90+ # The FSDP forward pre-hook has already unsharded the head. Each
91+ # chunk can produce a BF16 gradient before the hook widens it.
92+ if grad_hook is not None:
93+ leaf.grad_dtype = None
94+ 
95+ forward_hook = head.register_forward_pre_hook(prepare_head_grad)
96+ try:
97+ result = super().__call__(pred, labels, global_loss_token_counts, **loss_inputs)
98+ if accumulator is not None:
99+ raise RuntimeError("FSDP chunked loss did not reduce the accumulated head gradient")
100+ return result
101+ finally:
102+ forward_hook.remove()
103+ if grad_hook is not None and leaf is not None:
104+ grad_hook.remove()
105+ leaf.grad_dtype = torch.float32
@@ -23,6 +23,7 @@ import torch
23import torch.nn.functional as F23import torch.nn.functional as F
24from torch.distributed.tensor import DTensor24from torch.distributed.tensor import DTensor
25from torchtitan.models.base.module import Module25from torchtitan.models.base.module import Module
26+from torchtitan.models.common.linear import Linear # noqa: TC002 - Resolved by config introspection.
26 27 
27 28 
28def _local_tensor(tensor: torch.Tensor) -> torch.Tensor:29def _local_tensor(tensor: torch.Tensor) -> torch.Tensor:
@@ -324,6 +325,7 @@ class EngramContextGate(Module):
324 num_branches: int = 4325 num_branches: int = 4
325 norm_eps: float = 1e-5326 norm_eps: float = 1e-5
326 signed_sqrt_gate: bool = True327 signed_sqrt_gate: bool = True
328+ wkv: Linear.Config | None = None
327 329 
328 def __init__(self, config: Config):330 def __init__(self, config: Config):
329 super().__init__()331 super().__init__()
@@ -336,7 +338,11 @@ class EngramContextGate(Module):
336 # the published model stores them, so its weights load without a338 # the published model stores them, so its weights load without a
337 # bespoke reshape, and it is one GEMM instead of a batched matmul plus339 # bespoke reshape, and it is one GEMM instead of a batched matmul plus
338 # a linear.340 # a linear.
339- self.wkv = torch.nn.Parameter(torch.empty(config.hidden_size * (config.num_branches + 1), config.memory_dim))341+ self.wkv = (
342+ config.wkv.build()
343+ if config.wkv is not None
344+ else torch.nn.Parameter(torch.empty(config.hidden_size * (config.num_branches + 1), config.memory_dim))
345+ )
340 self.q_weight = torch.nn.Parameter(torch.empty(config.num_branches, config.hidden_size))346 self.q_weight = torch.nn.Parameter(torch.empty(config.num_branches, config.hidden_size))
341 self.k_weight = torch.nn.Parameter(torch.empty(config.num_branches, config.hidden_size))347 self.k_weight = torch.nn.Parameter(torch.empty(config.num_branches, config.hidden_size))
342 348 
@@ -345,22 +351,25 @@ class EngramContextGate(Module):
345 hidden_states_TMD: torch.Tensor,351 hidden_states_TMD: torch.Tensor,
346 memory_TE: torch.Tensor,352 memory_TE: torch.Tensor,
347 ) -> torch.Tensor:353 ) -> torch.Tensor:
348- kv_TX = F.linear(memory_TE, _local_tensor(self.wkv))354+ if isinstance(self.wkv, torch.nn.Module):
349- keys_TF, values_TD = kv_TX.split([self.num_branches * self.hidden_size, self.hidden_size], dim=-1)355+ kv_tx = self.wkv(memory_TE)
356+ else:
357+ kv_tx = F.linear(memory_TE, _local_tensor(self.wkv))
358+ keys_tf, values_td = kv_tx.split([self.num_branches * self.hidden_size, self.hidden_size], dim=-1)
350 # The inference reference accumulates the normalized dot product and359 # The inference reference accumulates the normalized dot product and
351 # residual in FP32, with only the projection in the activation dtype.360 # residual in FP32, with only the projection in the activation dtype.
352- keys_TMD = keys_TF.float().unflatten(-1, (self.num_branches, self.hidden_size))361+ keys_tmd = keys_tf.float().unflatten(-1, (self.num_branches, self.hidden_size))
353- queries_TMD = hidden_states_TMD.float()362+ queries_tmd = hidden_states_TMD.float()
354- norm_weight_MD = _local_tensor(self.q_weight).float() * _local_tensor(self.k_weight).float()363+ norm_weight_md = _local_tensor(self.q_weight).float() * _local_tensor(self.k_weight).float()
355- inverse_norm_TM = torch.rsqrt(queries_TMD.square().mean(-1) + self.norm_eps)364+ inverse_norm_tm = torch.rsqrt(queries_tmd.square().mean(-1) + self.norm_eps)
356- inverse_norm_TM = inverse_norm_TM * torch.rsqrt(keys_TMD.square().mean(-1) + self.norm_eps)365+ inverse_norm_tm = inverse_norm_tm * torch.rsqrt(keys_tmd.square().mean(-1) + self.norm_eps)
357- logits_TM = (queries_TMD * norm_weight_MD * keys_TMD).sum(-1)366+ logits_tm = (queries_tmd * norm_weight_md * keys_tmd).sum(-1)
358- logits_TM = logits_TM * inverse_norm_TM * self.hidden_size**-0.5367+ logits_tm = logits_tm * inverse_norm_tm * self.hidden_size**-0.5
359 if self.signed_sqrt_gate:368 if self.signed_sqrt_gate:
360- magnitude = logits_TM.abs().clamp_min(1e-6).sqrt()369+ magnitude = logits_tm.abs().clamp_min(1e-6).sqrt()
361- logits_TM = torch.where(logits_TM >= 0, magnitude, -magnitude)370+ logits_tm = torch.where(logits_tm >= 0, magnitude, -magnitude)
362- gates_TM1 = logits_TM.sigmoid().unsqueeze(-1)371+ gates_tm1 = logits_tm.sigmoid().unsqueeze(-1)
363- return gates_TM1 * values_TD.float().unsqueeze(-2)372+ return gates_tm1 * values_td.float().unsqueeze(-2)
364 373 
365 374 
366class Engram(Module):375class Engram(Module):
@@ -50,7 +50,9 @@ from torchtitan.experiments.graph_trainer.model import GraphTrainerModel
50from torchtitan.models.common.decoder import Decoder, TransformerBlock50from torchtitan.models.common.decoder import Decoder, TransformerBlock
51from torchtitan.models.common.linear import Linear51from torchtitan.models.common.linear import Linear
52 52 
53+from torchtitan_npu.config import ModelCompileConfig # noqa: TC001 - Resolved by config introspection.
53from torchtitan_npu.models.common.attention_metadata import GeometryAttentionMetadataMixin54from torchtitan_npu.models.common.attention_metadata import GeometryAttentionMetadataMixin
55+from torchtitan_npu.models.common.compile_policy import compiles_under_cp
54from torchtitan_npu.models.common.metadata import KernelFrame56from torchtitan_npu.models.common.metadata import KernelFrame
55 57 
56from .engram import Engram # noqa: TC00158from .engram import Engram # noqa: TC001
@@ -306,6 +308,8 @@ class DeepSeekV41Model(GeometryAttentionMetadataMixin, Decoder):
306 def _apply_fsdp(self, **kwargs):308 def _apply_fsdp(self, **kwargs):
307 from .parallelize import apply_deepseek_v4_1_fsdp309 from .parallelize import apply_deepseek_v4_1_fsdp
308 310 
311+ if self.config.block_compile is not None and compiles_under_cp(kwargs["parallelism_context"]):
312+ self.apply_model_compile(self.config.block_compile)
309 apply_deepseek_v4_1_fsdp(self, **kwargs)313 apply_deepseek_v4_1_fsdp(self, **kwargs)
310 314 
311 @dataclass(kw_only=True, slots=True)315 @dataclass(kw_only=True, slots=True)
@@ -321,6 +325,8 @@ class DeepSeekV41Model(GeometryAttentionMetadataMixin, Decoder):
321 candidate_block_size: int = 8325 candidate_block_size: int = 8
322 fp32_param_patterns: tuple[str, ...] = ()326 fp32_param_patterns: tuple[str, ...] = ()
323 """Parameter name patterns retained in FP32 under FSDP mixed precision."""327 """Parameter name patterns retained in FP32 under FSDP mixed precision."""
328+ block_compile: ModelCompileConfig | None = None
329+ """Compile decoder blocks after activation remat and before FSDP."""
324 330 
325 def __post_init__(self) -> None:331 def __post_init__(self) -> None:
326 if len(self.compress_ratios) != self.n_layers or len(self.layers) != self.n_layers:332 if len(self.compress_ratios) != self.n_layers or len(self.layers) != self.n_layers:
@@ -563,17 +569,21 @@ class DeepSeekV41MultimodalModel(DeepSeekV41Model):
563 extra_kwargs.update(vision_inputs)569 extra_kwargs.update(vision_inputs)
564 return inputs, labels, extra_kwargs, loss_kwargs570 return inputs, labels, extra_kwargs, loss_kwargs
565 571 
566- def apply_activation_checkpointing_extensions(self, policy) -> None:572+ def parallelize(self, **kwargs):
567- """Apply the shared AC policy to the V4.1 vision blocks.573+ activation_remat = kwargs.get("activation_remat")
574+ if activation_remat is not None:
575+ self.apply_activation_checkpointing_extensions(activation_remat)
576+ return super().parallelize(**kwargs)
568 577 
569- ``_wrap_block`` is private because the pinned torchtitan exposes no public hook578+ def apply_activation_checkpointing_extensions(self, policy) -> None:
570- for wrapping a block that is not part of a ``Decoder`` layer list.579+ """Apply activation remat before sharding the vision tower."""
571- """
572 for name, block in self.vision_encoder.blocks.named_children():580 for name, block in self.vision_encoder.blocks.named_children():
573- self.vision_encoder.blocks.register_module(581+ block.configure_remat_regions(policy.save_regions, policy.recompute_regions)
574- name,582+ block.forward = remat.checkpoint(
575- policy._wrap_block(block, base_fqn=f"vision_encoder.blocks.{name}"),583+ region_name=f"vision_encoder.blocks.{name}",
576- )584+ determinism_check=policy.determinism_check,
585+ preserve_rng_state=policy.preserve_rng_state,
586+ )(block.forward)
577 587 
578 def apply_fsdp_extensions(self, *, dp_mesh, dp_mesh_dims, training, parallelism, parallelism_context) -> None:588 def apply_fsdp_extensions(self, *, dp_mesh, dp_mesh_dims, training, parallelism, parallelism_context) -> None:
579 """FSDP-wrap the V4.1 vision tower before the shared decoder wrapper."""589 """FSDP-wrap the V4.1 vision tower before the shared decoder wrapper."""
@@ -8,7 +8,7 @@
8from dataclasses import dataclass8from dataclasses import dataclass
9 9 
10import torch10import torch
11-from torchtitan.models.common.moe import TokenChoiceTopKRouter11+from torchtitan.models.common.moe import RoundRobinTokenChoiceTopKRouter, TokenChoiceTopKRouter
12 12 
13 13 
14class DeepSeekV41Router(TokenChoiceTopKRouter):14class DeepSeekV41Router(TokenChoiceTopKRouter):
@@ -54,3 +54,13 @@ class DeepSeekV41Router(TokenChoiceTopKRouter):
54 def _topk(self, scores_for_choice_TE: torch.Tensor) -> torch.Tensor:54 def _topk(self, scores_for_choice_TE: torch.Tensor) -> torch.Tensor:
55 """Select experts with an optional kernel override."""55 """Select experts with an optional kernel override."""
56 return scores_for_choice_TE.topk(self.top_k, dim=-1, sorted=self.sorted_topk).indices56 return scores_for_choice_TE.topk(self.top_k, dim=-1, sorted=self.sorted_topk).indices
57+ 
58+ 
59+class RoundRobinDeepSeekV41Router(DeepSeekV41Router):
60+ """Use fixed expert assignments while preserving the V4.1 router parameters."""
61+ 
62+ @dataclass(kw_only=True, slots=True)
63+ class Config(DeepSeekV41Router.Config):
64+ pass
65+ 
66+ _select_experts = RoundRobinTokenChoiceTopKRouter._select_experts
@@ -259,13 +259,12 @@ def _apply_compile_v4_1(model, *, compile_config: ModelCompileConfig) -> None:
259 # the dispatcher's dispatch/combine must instead run eagerly outside the259 # the dispatcher's dispatch/combine must instead run eagerly outside the
260 # graph (fullgraph=False). aot_eager replays the aten ops verbatim and always260 # graph (fullgraph=False). aot_eager replays the aten ops verbatim and always
261 # keeps fullgraph=True.261 # keeps fullgraph=True.
262- # TODO(compile): Restore force-balanced detection when model compile is262+ from .moe import RoundRobinDeepSeekV41Router
263- # re-enabled. Upstream v0.4.0 removed --debug.moe-force-load-balance and the263+ 
264- # router hook; the replacement is RoundRobinTokenChoiceTopKRouter, which the264+ blocks = list(model.layers.children())
265- # V4/V4.1 recipes must select explicitly. Until then treat routing as265+ routers = (getattr(getattr(block, "feed_forward", None), "router", None) for block in blocks)
266- # data-dependent for inductor.266+ force_balanced_moe = bool(blocks) and all(isinstance(router, RoundRobinDeepSeekV41Router) for router in routers)
267- force_balanced_moe = False267+ fullgraph = (compile_config.backend != "inductor" or force_balanced_moe) and compile_config.fullgraph
268- fullgraph = compile_config.backend != "inductor" or force_balanced_moe
269 configure_dispatchers_for_compile(268 configure_dispatchers_for_compile(
270 model, eager_all_to_all=compile_config.backend == "inductor" and not force_balanced_moe269 model, eager_all_to_all=compile_config.backend == "inductor" and not force_balanced_moe
271 )270 )
@@ -275,22 +274,16 @@ def _apply_compile_v4_1(model, *, compile_config: ModelCompileConfig) -> None:
275 # Skip the unbacked-SymInt runtime assertions (Eq(u32+..., T*K))274 # Skip the unbacked-SymInt runtime assertions (Eq(u32+..., T*K))
276 # that inductor derives from the tracing run's expert distribution.275 # that inductor derives from the tracing run's expert distribution.
277 setattr(torch._inductor.config, "do_not_emit_runtime_assertions", True) # noqa: B010276 setattr(torch._inductor.config, "do_not_emit_runtime_assertions", True) # noqa: B010
278- if not force_balanced_moe:
279- # The MoE communication (all_to_all_single with data-dependent
280- # splits) runs eagerly: wrap the NPU dispatcher's dispatch/combine
281- # so dynamo treats them as opaque and graph-breaks around them.
282- # aot_eager keeps fullgraph=True and needs no wrapping.
283- from torchtitan_npu.override.common.token_dispatcher import AscAllToAllTokenDispatcher
284 277 
285- AscAllToAllTokenDispatcher.dispatch = torch._dynamo.disable(recursive=True)(278+ from torchtitan_npu.patches.torch_npu.device import is_a5
286- AscAllToAllTokenDispatcher.dispatch
287- )
288- AscAllToAllTokenDispatcher.combine = torch._dynamo.disable(recursive=True)(
289- AscAllToAllTokenDispatcher.combine
290- )
291 279 
292- for layer_id, transformer_block in model.layers.named_children():280+ ascendc = compile_config.backend == "inductor" and is_a5()
293- transformer_block.compile(backend=compile_config.backend, fullgraph=fullgraph, dynamic=False)281+ for block in blocks:
282+ # Fusing the Engram and mHC backward reductions on A5 needs a 58.75 GiB workspace at 8K tokens.
283+ options = None
284+ if ascendc and getattr(block, "engram", None) is not None:
285+ options = {"max_fusion_size": 1, "realize_opcount_threshold": 1, "realize_reads_threshold": 1}
286+ block.compile(backend=compile_config.backend, fullgraph=fullgraph, dynamic=False, options=options)
294 287 
295 logger.info(288 logger.info(
296 f"Compiling each V4.1 TransformerBlock with torch.compile "289 f"Compiling each V4.1 TransformerBlock with torch.compile "
@@ -68,13 +68,13 @@ def set_engram_sharding_config(engram_cfg, *, enable_ep: bool, enable_sp: bool)
68 }68 }
69 engram_cfg.table.sharding_config = ShardingConfig(state_shardings=table_state)69 engram_cfg.table.sharding_config = ShardingConfig(state_shardings=table_state)
70 70 
71- engram_cfg.gate.sharding_config = ShardingConfig(71+ gate = engram_cfg.gate
72- state_shardings={72+ gate_state = {"q_weight": dense_param_rep, "k_weight": dense_param_rep}
73- "wkv": dense_param_rep,73+ if gate.wkv is None:
74- "q_weight": dense_param_rep,74+ gate_state["wkv"] = dense_param_rep
75- "k_weight": dense_param_rep,75+ else:
76- }76+ gate.wkv.sharding_config = ShardingConfig(state_shardings={"weight": dense_param_rep})
77- )77+ gate.sharding_config = ShardingConfig(state_shardings=gate_state)
78 hidden = _engram_hidden_placement(enable_sp=enable_sp)78 hidden = _engram_hidden_placement(enable_sp=enable_sp)
79 token_src = dense_activation_placement(tp=spmd.R, cp=spmd.S(0))79 token_src = dense_activation_placement(tp=spmd.R, cp=spmd.S(0))
80 token_dst = dense_token_ids_sequence_parallel_placement() if enable_sp else token_src80 token_dst = dense_token_ids_sequence_parallel_placement() if enable_sp else token_src
@@ -51,6 +51,8 @@ class DeepSeekV41StateDictAdapter(DeepSeekPEFTAdapter, DeepSeekV3StateDictAdapte
51 self._engram_tables = {51 self._engram_tables = {
52 i: layer.engram.table for i, layer in enumerate(model_config.layers) if layer.engram is not None52 i: layer.engram.table for i, layer in enumerate(model_config.layers) if layer.engram is not None
53 }53 }
54+ layers = model_config.layers
55+ self._linear_engram_layers = {i for i in self._engram_tables if layers[i].engram.gate.wkv is not None}
54 super().__init__(model_config, hf_assets_path)56 super().__init__(model_config, hf_assets_path)
55 self._initialize_peft(model_config)57 self._initialize_peft(model_config)
56 58 
@@ -190,6 +192,8 @@ class DeepSeekV41StateDictAdapter(DeepSeekPEFTAdapter, DeepSeekV3StateDictAdapte
190 raise ValueError(f"HF checkpoint contains Engram for unconfigured layer {layer_id}")192 raise ValueError(f"HF checkpoint contains Engram for unconfigured layer {layer_id}")
191 abstract = re.sub(r"(\d+)", "{}", key, count=1)193 abstract = re.sub(r"(\d+)", "{}", key, count=1)
192 local_key = self.from_hf_map[abstract].format(layer_id)194 local_key = self.from_hf_map[abstract].format(layer_id)
195+ if key.endswith(".engram.wkv.weight") and layer_id in self._linear_engram_layers:
196+ local_key += ".weight"
193 if hasattr(value, "_engram_valid_rows"):197 if hasattr(value, "_engram_valid_rows"):
194 value[value._engram_valid_rows :].zero_()198 value[value._engram_valid_rows :].zero_()
195 state_dict[local_key] = value199 state_dict[local_key] = value
@@ -288,6 +292,9 @@ class DeepSeekV41StateDictAdapter(DeepSeekPEFTAdapter, DeepSeekV3StateDictAdapte
288 else value[:logical_rows]292 else value[:logical_rows]
289 )293 )
290 294 
295+ elif key.endswith(".engram.gate.wkv.weight"):
296+ hf_state_dict[key.replace(".engram.gate.wkv.weight", ".engram.wkv.weight")] = value
297+ 
291 elif any(t in key for t in ("compressor", "indexer")):298 elif any(t in key for t in ("compressor", "indexer")):
292 hf_state_dict[to_hf_map[key]] = value299 hf_state_dict[to_hf_map[key]] = value
293 300 
@@ -40,6 +40,19 @@ def sort_indices_and_scores(
40 return indices, scores.gather(-1, order)40 return indices, scores.gather(-1, order)
41 41 
42 42 
43+# Keep the vendor backward as an external call in A5 Inductor graphs. Its
44+# multi-output ABI must not be folded into a generated elementwise kernel.
45+_compiled_grad = None
46+_vendor_packet = getattr(torch.ops.cann_ops_transformer, "sparse_lightning_indexer_kl_loss_grad", None)
47+if _IS_A5 and isinstance(_vendor_packet, torch._ops.OpOverloadPacket):
48+ _vendor_grad = _vendor_packet.default
49+ _indexer_ops = torch.library.Library("torchtitan_npu", "FRAGMENT")
50+ _indexer_ops.define("sparse_indexer_kl_grad(" + str(_vendor_grad._schema).split("(", 1)[1])
51+ _indexer_ops.impl("sparse_indexer_kl_grad", _vendor_grad, "CompositeExplicitAutograd")
52+ _indexer_ops.impl("sparse_indexer_kl_grad", _vendor_grad, "Meta")
53+ _compiled_grad = torch.ops.torchtitan_npu.sparse_indexer_kl_grad
54+ 
55+ 
43class _LightningIndexerTND(torch.autograd.Function):56class _LightningIndexerTND(torch.autograd.Function):
44 @staticmethod57 @staticmethod
45 def forward(ctx, q, k, w, topk, attention_metadata, options): # pyrefly: ignore [bad-override]58 def forward(ctx, q, k, w, topk, attention_metadata, options): # pyrefly: ignore [bad-override]
@@ -64,7 +77,12 @@ class _LightningIndexerTND(torch.autograd.Function):
64 metadata = ctx.attention_metadata.aicpu_metadata.lightning_indexer.bwd77 metadata = ctx.attention_metadata.aicpu_metadata.lightning_indexer.bwd
65 if metadata is None:78 if metadata is None:
66 raise ValueError("the fused selector needs the entry's backward metadata")79 raise ValueError("the fused selector needs the entry's backward metadata")
67- dq, dk, dw, _ = torch.ops.cann_ops_transformer.sparse_lightning_indexer_kl_loss_grad(80+ grad_op = (
81+ _compiled_grad
82+ if _compiled_grad is not None and torch.compiler.is_compiling()
83+ else torch.ops.cann_ops_transformer.sparse_lightning_indexer_kl_loss_grad
84+ )
85+ dq, dk, dw, _ = grad_op(
68 q=q,86 q=q,
69 k=k,87 k=k,
70 w=w,88 w=w,
@@ -15,7 +15,7 @@ from torchtitan.components.data import (
15 HuggingFaceRandomAccessSource,15 HuggingFaceRandomAccessSource,
16 SingleDatasetConfig,16 SingleDatasetConfig,
17)17)
18-from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss18+from torchtitan.components.loss import CrossEntropyLoss
19from torchtitan.components.optim import AdamW, LRSchedulersContainer19from torchtitan.components.optim import AdamW, LRSchedulersContainer
20from torchtitan.components.tokenizer import HuggingFaceTokenizer20from torchtitan.components.tokenizer import HuggingFaceTokenizer
21from torchtitan.config import CommConfig, OverrideConfig, derive21from torchtitan.config import CommConfig, OverrideConfig, derive
@@ -28,6 +28,7 @@ from torchtitan.models.common.config_utils import decoder_vocab_size
28from torchtitan.observability.metrics import MetricsProcessor28from torchtitan.observability.metrics import MetricsProcessor
29 29 
30from torchtitan_npu.config import (30from torchtitan_npu.config import (
31+ ModelCompileConfig,
31 MuonOptimizerProfile,32 MuonOptimizerProfile,
32 OptimConfig,33 OptimConfig,
33 OptimizerConfig,34 OptimizerConfig,
@@ -39,6 +40,7 @@ from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import
39from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler40from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler
40from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx41from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
41from torchtitan_npu.models.common.alignment import AlignedTextProcessor, compression_alignment42from torchtitan_npu.models.common.alignment import AlignedTextProcessor, compression_alignment
43+from torchtitan_npu.models.common.chunked_loss import FP32HeadGradChunkedLoss
42from torchtitan_npu.models.common.muon import make_expert_layout, make_owned_layout, with_lora_compute_layouts44from torchtitan_npu.models.common.muon import make_expert_layout, make_owned_layout, with_lora_compute_layouts
43from torchtitan_npu.models.deepseek_v4_1 import EngramArgs, build_model_config45from torchtitan_npu.models.deepseek_v4_1 import EngramArgs, build_model_config
44from torchtitan_npu.models.deepseek_v4_1.checkpoint import DeepSeekV41LoRACheckpointManager46from torchtitan_npu.models.deepseek_v4_1.checkpoint import DeepSeekV41LoRACheckpointManager
@@ -135,7 +137,8 @@ def _v41_muon_profile(model: DeepSeekV41Model.Config) -> MuonOptimizerProfile:
135 dense_shardings[f"layers.{layer_id}.hc_ffn_pre.hc_fn"] = owned137 dense_shardings[f"layers.{layer_id}.hc_ffn_pre.hc_fn"] = owned
136 if layer_config.engram is not None:138 if layer_config.engram is not None:
137 # q_weight/k_weight are normalization scales, not projections.139 # q_weight/k_weight are normalization scales, not projections.
138- dense_shardings[f"layers.{layer_id}.engram.gate.wkv"] = owned140+ projection = "wkv.weight" if layer_config.engram.gate.wkv is not None else "wkv"
141+ dense_shardings[f"layers.{layer_id}.engram.gate.{projection}"] = owned
139 routed_shardings = {142 routed_shardings = {
140 f"layers.{layer_id}.feed_forward.routed_experts.{projection}": expert_sharding143 f"layers.{layer_id}.feed_forward.routed_experts.{projection}": expert_sharding
141 for projection in routed_expert_projections144 for projection in routed_expert_projections
@@ -161,7 +164,7 @@ def _v41_muon_profile(model: DeepSeekV41Model.Config) -> MuonOptimizerProfile:
161 rf"feed_forward\.shared_experts\.(?:{'|'.join(expert_projections)})\.weight|"164 rf"feed_forward\.shared_experts\.(?:{'|'.join(expert_projections)})\.weight|"
162 rf"feed_forward\.routed_experts\.(?:{'|'.join(routed_expert_projections)})|"165 rf"feed_forward\.routed_experts\.(?:{'|'.join(routed_expert_projections)})|"
163 r"feed_forward\.router\.gate\.weight|"166 r"feed_forward\.router\.gate\.weight|"
164- r"engram\.gate\.wkv|"167+ r"engram\.gate\.wkv(?:\.weight)?|"
165 rf"(?:{'|'.join(hc_pre_modules)})\.hc_fn" + r")$"168 rf"(?:{'|'.join(hc_pre_modules)})\.hc_fn" + r")$"
166 )169 )
167 profile = MuonOptimizerProfile(170 profile = MuonOptimizerProfile(
@@ -382,7 +385,7 @@ def _make_trainer_config(
382 max_context_length=seq_len,385 max_context_length=seq_len,
383 steps=100,386 steps=100,
384 ),387 ),
385- loss=ChunkedLossWrapper.Config(388+ loss=FP32HeadGradChunkedLoss.Config(
386 loss_fn=CrossEntropyLoss.Config(389 loss_fn=CrossEntropyLoss.Config(
387 global_vocab_size=decoder_vocab_size(model),390 global_vocab_size=decoder_vocab_size(model),
388 ),391 ),
@@ -525,6 +528,45 @@ def deepseek_v4_1_flash_40layers_24experts_multimodal_block_fp8() -> TrainerEx.C
525 return config528 return config
526 529 
527 530 
531+def deepseek_v4_1_flash_8p_cpt_4k_a5_balanced_compile() -> TrainerEx.Config:
532+ """Run the 10-step A5 block-FP8 benchmark with round-robin expert assignment."""
533+ from torchtitan.models.common.linear import Linear
534+ 
535+ from torchtitan_npu.models.deepseek_v4_1.moe import RoundRobinDeepSeekV41Router
536+ from torchtitan_npu.models.deepseek_v4_1.sharding import set_engram_sharding_config
537+ 
538+ config = deepseek_v4_1_flash_40layers_24experts_multimodal_block_fp8()
539+ model = config.model
540+ assert isinstance(model, DeepSeekV41Model.Config)
541+ model.block_compile = ModelCompileConfig()
542+ tokens = 2 * config.training.max_context_length
543+ config.training.num_tokens_per_microbatch_per_dp_rank = tokens
544+ config.training.steps = 10
545+ config.optim.lr_scheduler.total_steps = 40
546+ config.optim.lr_scheduler.warmup_steps = 2
547+ config.optim.lr_scheduler.decay_ratio = 1.0
548+ config.extension.quantization.fsdp_prequantize_fqns = [*_A5_PREQUANTIZE_FQNS, ".engram.gate.wkv"]
549+ for layer in model.layers:
550+ moe = layer.feed_forward
551+ moe.router = derive(moe.router, RoundRobinDeepSeekV41Router.Config)
552+ moe.routed_experts.token_dispatcher.num_max_tokens_per_rank = tokens
553+ if layer.engram is not None:
554+ gate = layer.engram.gate
555+ gate.wkv = Linear.Config(
556+ in_features=gate.memory_dim,
557+ out_features=(gate.num_branches + 1) * gate.hidden_size,
558+ bias=False,
559+ inplace_wgrad_accum=False,
560+ param_init={"weight": gate.param_init["wkv"]},
561+ )
562+ gate.param_init = {k: v for k, v in gate.param_init.items() if k != "wkv"}
563+ set_engram_sharding_config(
564+ layer.engram, enable_ep=True, enable_sp=config.parallelism.enable_sequence_parallel
565+ )
566+ config.optim.optimizer = _v41_optimizer_config(model)
567+ return config
568+ 
569+ 
528def deepseek_v4_1_flash_40layers_24experts_multimodal_qat() -> TrainerEx.Config:570def deepseek_v4_1_flash_40layers_24experts_multimodal_qat() -> TrainerEx.Config:
529 """Build the 8-rank A5 multimodal QAT case with MXFP4 and quantized sparse attention."""571 """Build the 8-rank A5 multimodal QAT case with MXFP4 and quantized sparse attention."""
530 config = deepseek_v4_1_flash_40layers_24experts_multimodal_block_fp8()572 config = deepseek_v4_1_flash_40layers_24experts_multimodal_block_fp8()