Merged
[refactor] 退役 DeepSeek-V4 旧注意力 backend 转换入口 #1292
hanboyouAdd on 20 days ago
[refactor] 退役 DeepSeek-V4 旧注意力 backend 转换入口 #1292
Merged
Total: 7 files changed+36-1033
| @@ -51,11 +51,10 @@ def _build_model_config(num_experts=NUM_EXPERTS, num_layers=N_LAYERS, num_mtp_la | |||
| 51 | 51 | ||
| 52 | 52 | ||
| 53 | def _lora_model_config(*, num_experts=2, num_layers=1, targets=None): | 53 | def _lora_model_config(*, num_experts=2, num_layers=1, targets=None): |
| 54 | - from torchtitan_npu.models.deepseek_v4.backend import with_npu_attention_backend | ||
| 55 | from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform | 54 | from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform |
| 56 | 55 | ||
| 57 | transform = deepseek_v4_lora_transform(rank=8, alpha=16) | 56 | transform = deepseek_v4_lora_transform(rank=8, alpha=16) |
| 58 | if targets is not None: | 57 | if targets is not None: |
| 59 | transform.target_modules = targets | 58 | transform.target_modules = targets |
| 60 | - config = with_npu_attention_backend(_build_model_config(num_experts=num_experts, num_layers=num_layers)) | 59 | + config = _build_model_config(num_experts=num_experts, num_layers=num_layers) |
| 61 | return transform.transform(config) | 60 | return transform.transform(config) |
| @@ -1,77 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | -# SPDX-License-Identifier: BSD-3-Clause | ||
| 3 | - | ||
| 4 | -import pytest | ||
| 5 | -import torch | ||
| 6 | -from torchtitan.config.parallelism import ParallelismConfig | ||
| 7 | -from torchtitan.models.deepseek_v4 import build_model_config | ||
| 8 | -from torchtitan.models.deepseek_v4.attention import DeepSeekV4Attention | ||
| 9 | -from torchtitan.models.deepseek_v4.state_dict_adapter import DeepSeekV4StateDictAdapter as NativeStateDictAdapter | ||
| 10 | - | ||
| 11 | -from torchtitan_npu.models.deepseek_v4.attention import NPUAttention | ||
| 12 | -from torchtitan_npu.models.deepseek_v4.backend import ( | ||
| 13 | - NPUBackendDeepSeekV4Model, | ||
| 14 | - to_npu_attention_config, | ||
| 15 | - with_npu_attention_backend, | ||
| 16 | -) | ||
| 17 | - | ||
| 18 | - | ||
| 19 | -def test_npu_backend_selection_preserves_native_source_and_adapts_main_and_mtp(): | ||
| 20 | - native = build_model_config( | ||
| 21 | - "debugmodel", seq_len=128, n_mtp_layers=1, parallelism=ParallelismConfig(), indexer_loss_coeff=0 | ||
| 22 | - ) | ||
| 23 | - native_attention = native.layers[0].attention | ||
| 24 | - backend = with_npu_attention_backend(native) | ||
| 25 | - | ||
| 26 | - assert type(native_attention) is DeepSeekV4Attention.Config | ||
| 27 | - assert native.layers[0].attention is native_attention | ||
| 28 | - assert native_attention.compress_ratio == 0 | ||
| 29 | - assert native_attention.rope.split == 0 | ||
| 30 | - assert isinstance(backend, NPUBackendDeepSeekV4Model.Config) | ||
| 31 | - assert all(isinstance(layer.attention, NPUAttention.Config) for layer in (*backend.layers, *backend.mtp_layers)) | ||
| 32 | - assert backend.layers[0].attention.compress_ratio == 1 | ||
| 33 | - assert backend.layers[0].attention.rope.split == native_attention.head_dim - native_attention.rope_head_dim | ||
| 34 | - assert backend.layers[3].attention.compressor is not None | ||
| 35 | - assert backend.layers[3].attention.compressor.compress_ratio == 128 | ||
| 36 | - assert backend.layers[2].attention.lightning_indexer is not None | ||
| 37 | - assert backend.layers[0].attention.lightning_indexer is None | ||
| 38 | - | ||
| 39 | - | ||
| 40 | -def test_npu_backend_attention_keeps_projection_storage_and_selects_bare_sink(): | ||
| 41 | - config = build_model_config("debugmodel", seq_len=128, parallelism=ParallelismConfig(), indexer_loss_coeff=0) | ||
| 42 | - native_config = config.layers[0].attention | ||
| 43 | - backend_config = to_npu_attention_config(native_config) | ||
| 44 | - with torch.device("meta"): | ||
| 45 | - native = native_config.build() | ||
| 46 | - backend = backend_config.build() | ||
| 47 | - | ||
| 48 | - assert native.wo_a.weight.shape == backend.wo_a.weight.shape | ||
| 49 | - assert native.attn_sink.weight.shape == (native_config.n_heads, 1) | ||
| 50 | - assert backend.attn_sink.shape == (native_config.n_heads,) | ||
| 51 | - assert "attn_sink.weight" in native.state_dict() | ||
| 52 | - assert "attn_sink" in backend.state_dict() | ||
| 53 | - | ||
| 54 | - | ||
| 55 | -def test_npu_backend_selects_matching_hf_checkpoint_names_and_sink_rank(): | ||
| 56 | - native = build_model_config("debugmodel", seq_len=128, parallelism=ParallelismConfig(), indexer_loss_coeff=0) | ||
| 57 | - backend = with_npu_attention_backend(native) | ||
| 58 | - sink = torch.arange(native.layers[0].attention.n_heads, dtype=torch.float32) | ||
| 59 | - ape = torch.arange(4, dtype=torch.float32) | ||
| 60 | - hf_state = {"layers.0.attn.attn_sink": sink, "layers.3.attn.compressor.ape": ape} | ||
| 61 | - native_state = NativeStateDictAdapter(native, None).from_hf(hf_state) | ||
| 62 | - backend_adapter = NPUBackendDeepSeekV4Model.state_dict_adapter_cls(backend, None) | ||
| 63 | - backend_state = backend_adapter.from_hf(hf_state) | ||
| 64 | - | ||
| 65 | - assert torch.equal(native_state["layers.0.attention.attn_sink.weight"], sink[:, None]) | ||
| 66 | - assert torch.equal(backend_state["layers.0.attention.attn_sink"], sink) | ||
| 67 | - assert torch.equal(native_state["layers.3.attention.compressor_128.ape"], ape) | ||
| 68 | - assert torch.equal(backend_state["layers.3.attention.compressor.ape"], ape) | ||
| 69 | - round_trip = backend_adapter.to_hf(backend_state) | ||
| 70 | - assert set(round_trip) == set(hf_state) | ||
| 71 | - assert all(torch.equal(round_trip[name], value) for name, value in hf_state.items()) | ||
| 72 | - | ||
| 73 | - | ||
| 74 | -def test_npu_backend_rejects_untranslated_indexer_objective(): | ||
| 75 | - config = build_model_config("debugmodel", seq_len=128, parallelism=ParallelismConfig()) | ||
| 76 | - with pytest.raises(ValueError, match="indexer_loss_coeff=0"): | ||
| 77 | - to_npu_attention_config(config.layers[2].attention) | ||
| @@ -10,6 +10,8 @@ from torchtitan.models.common.decoder_sharding import dense_param_placement | |||
| 10 | from torchtitan.models.common.linear import GroupedLinear | 10 | from torchtitan.models.common.linear import GroupedLinear |
| 11 | 11 | ||
| 12 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _lora_model_config | 12 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _lora_model_config |
| 13 | +from torchtitan_npu.models.common.deepseek_lora import BatchedLinearLoRA | ||
| 14 | +from torchtitan_npu_recipes.models.deepseek_v4_1 import deepseek_v4_1_debugmodel_lora | ||
| 13 | 15 | ||
| 14 | 16 | ||
| 15 | @pytest.fixture(autouse=True) | 17 | @pytest.fixture(autouse=True) |
| @@ -29,14 +31,28 @@ def _cpu_grouped_mm(self, *, input_RI, weight_EOI, offsets_E): | |||
| 29 | ) | 31 | ) |
| 30 | 32 | ||
| 31 | 33 | ||
| 32 | -@pytest.mark.parametrize("kind", ["dense", "batched", "grouped"], ids=["dense", "per-head", "routed"]) | 34 | +@pytest.mark.parametrize( |
| 35 | + "model,kind", | ||
| 36 | + [ | ||
| 37 | + pytest.param("dsv4", "dense", id="dsv4-dense"), | ||
| 38 | + pytest.param( | ||
| 39 | + "dsv4", | ||
| 40 | + "batched", | ||
| 41 | + marks=pytest.mark.skip(reason="Native DSV4 wo_a uses Linear; batched LoRA is covered by V4.1."), | ||
| 42 | + id="dsv4-per-group", | ||
| 43 | + ), | ||
| 44 | + pytest.param("dsv4", "grouped", id="dsv4-routed"), | ||
| 45 | + pytest.param("dsv4_1", "batched", id="v41-per-group"), | ||
| 46 | + ], | ||
| 47 | +) | ||
| 33 | @pytest.mark.parametrize("replicated", [False, True], ids=["unsharded", "replicated"]) | 48 | @pytest.mark.parametrize("replicated", [False, True], ids=["unsharded", "replicated"]) |
| 34 | -def test_standard_lora_projection_output_and_gradients_match_independent_formula(kind, replicated, monkeypatch): | 49 | +def test_standard_lora_projection_output_and_gradients_match_independent_formula(model, kind, replicated, monkeypatch): |
| 35 | - config = _lora_model_config() | 50 | + config = deepseek_v4_1_debugmodel_lora().model if model == "dsv4_1" else _lora_model_config() |
| 36 | if kind == "dense": | 51 | if kind == "dense": |
| 37 | projection = config.layers[0].attention.wq_a | 52 | projection = config.layers[0].attention.wq_a |
| 38 | elif kind == "batched": | 53 | elif kind == "batched": |
| 39 | projection = config.layers[0].attention.wo_a | 54 | projection = config.layers[0].attention.wo_a |
| 55 | + assert isinstance(projection, BatchedLinearLoRA.Config) | ||
| 40 | else: | 56 | else: |
| 41 | projection = config.layers[0].feed_forward.routed_experts.w13 | 57 | projection = config.layers[0].feed_forward.routed_experts.w13 |
| 42 | monkeypatch.setattr(GroupedLinear, "_grouped_mm", _cpu_grouped_mm) | 58 | monkeypatch.setattr(GroupedLinear, "_grouped_mm", _cpu_grouped_mm) |
| @@ -47,10 +63,14 @@ def test_standard_lora_projection_output_and_gradients_match_independent_formula | |||
| 47 | for adapter in (module.lora_a, module.lora_b): | 63 | for adapter in (module.lora_a, module.lora_b): |
| 48 | assert adapter._sharding_config.state_shardings["weight"] == dense_param_placement(tp=spmd.R) | 64 | assert adapter._sharding_config.state_shardings["weight"] == dense_param_placement(tp=spmd.R) |
| 49 | module.init_states(buffer_device=torch.device("cpu")) | 65 | module.init_states(buffer_device=torch.device("cpu")) |
| 66 | + if kind == "batched": | ||
| 67 | + module = module.to(dtype=torch.float64) | ||
| 50 | with torch.no_grad(): | 68 | with torch.no_grad(): |
| 69 | + if kind == "batched": | ||
| 70 | + module.lora_a.weight.normal_(std=0.1) | ||
| 51 | module.lora_b.weight.normal_(std=0.1) | 71 | module.lora_b.weight.normal_(std=0.1) |
| 52 | shape = (5, projection.n_heads, projection.in_features) if kind == "batched" else (5, projection.in_features) | 72 | shape = (5, projection.n_heads, projection.in_features) if kind == "batched" else (5, projection.in_features) |
| 53 | - inputs = torch.randn(shape, requires_grad=True) | 73 | + inputs = torch.randn(shape, dtype=module.weight.dtype, requires_grad=True) |
| 54 | a, b = module.lora_a.weight, module.lora_b.weight | 74 | a, b = module.lora_a.weight, module.lora_b.weight |
| 55 | if kind == "grouped": | 75 | if kind == "grouped": |
| 56 | offsets = torch.tensor([2, 5], dtype=torch.int32) | 76 | offsets = torch.tensor([2, 5], dtype=torch.int32) |
| @@ -61,16 +81,21 @@ def test_standard_lora_projection_output_and_gradients_match_independent_formula | |||
| 61 | expected = base + 2 * torch.einsum("tr,tsor->tso", hidden, b[experts]) | 81 | expected = base + 2 * torch.einsum("tr,tsor->tso", hidden, b[experts]) |
| 62 | elif kind == "batched": | 82 | elif kind == "batched": |
| 63 | actual = module(inputs) | 83 | actual = module(inputs) |
| 64 | - base = torch.einsum("thi,hoi->tho", inputs, module.weight.view(projection.n_heads, projection.out_features, -1)) | 84 | + weights = module.weight.view(projection.n_heads, projection.out_features, projection.in_features) |
| 65 | - hidden = torch.einsum("thi,ri->thr", inputs, a) | 85 | + group_b = b.view(projection.n_heads, projection.out_features, projection.rank) |
| 66 | - expected = base + 2 * torch.einsum( | 86 | + expected = torch.stack( |
| 67 | - "thr,hor->tho", hidden, b.view(projection.n_heads, projection.out_features, -1) | 87 | + [ |
| 88 | + inputs[:, group] @ weights[group].T | ||
| 89 | + + (projection.alpha / projection.rank) * (inputs[:, group] @ a.T @ group_b[group].T) | ||
| 90 | + for group in range(projection.n_heads) | ||
| 91 | + ], | ||
| 92 | + dim=1, | ||
| 68 | ) | 93 | ) |
| 69 | else: | 94 | else: |
| 70 | actual = module(inputs) | 95 | actual = module(inputs) |
| 71 | expected = F.linear(inputs, module.weight) + 2 * (inputs @ a.T @ b.T) | 96 | expected = F.linear(inputs, module.weight) + 2 * (inputs @ a.T @ b.T) |
| 72 | torch.testing.assert_close(actual, expected) | 97 | torch.testing.assert_close(actual, expected) |
| 73 | - upstream = torch.linspace(-0.5, 0.7, actual.numel()).reshape_as(actual) | 98 | + upstream = torch.linspace(-0.5, 0.7, actual.numel(), dtype=actual.dtype).reshape_as(actual) |
| 74 | actual_grads = torch.autograd.grad(actual, (inputs, a, b), upstream, retain_graph=True) | 99 | actual_grads = torch.autograd.grad(actual, (inputs, a, b), upstream, retain_graph=True) |
| 75 | expected_grads = torch.autograd.grad(expected, (inputs, a, b), upstream) | 100 | expected_grads = torch.autograd.grad(expected, (inputs, a, b), upstream) |
| 76 | for actual_grad, expected_grad in zip(actual_grads, expected_grads, strict=True): | 101 | for actual_grad, expected_grad in zip(actual_grads, expected_grads, strict=True): |
| @@ -1,360 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | -# | ||
| 3 | -# This source code is licensed under the BSD-style license found in the | ||
| 4 | -# LICENSE file in the root directory of this source tree. | ||
| 5 | - | ||
| 6 | -"""CPU contract of DeepSeek-V4's backend-owned metadata seam. | ||
| 7 | - | ||
| 8 | -The sparse-attention core's own config builds what it consumes (upstream #4897): the | ||
| 9 | -reference tier the packed contract, the fused AscendC tier that contract plus this | ||
| 10 | -geometry's kernel records. The decoder builds one entry per backend geometry for the | ||
| 11 | -whole microbatch, and the fused entry's own ``prepare_cp_metadata`` re-derives this | ||
| 12 | -rank's copy (upstream #4617). The test keeps the contract's two ends -- per-geometry | ||
| 13 | -entries and the rank-local rebuild -- and drops the per-field detail. | ||
| 14 | -""" | ||
| 15 | - | ||
| 16 | -from itertools import pairwise | ||
| 17 | - | ||
| 18 | -import pytest | ||
| 19 | -import torch | ||
| 20 | - | ||
| 21 | -from torchtitan_npu.models.common.restore import DOC_CHUNK_LAYOUT | ||
| 22 | -from torchtitan_npu.models.deepseek_v4 import _make_v4_config | ||
| 23 | -from torchtitan_npu.models.deepseek_v4.attention import CompressedSparseInnerAttention | ||
| 24 | -from torchtitan_npu.models.deepseek_v4.backend import with_npu_attention_backend | ||
| 25 | -from torchtitan_npu.models.deepseek_v4.metadata import DeepSeekV4Metadata | ||
| 26 | -from torchtitan_npu.models.deepseek_v4.sharding import set_deepseek_v4_sharding_config | ||
| 27 | -from torchtitan_npu.override import _IS_A5 | ||
| 28 | -from torchtitan_npu.override.deepseek_v4.metadata import AicpuGeometry, AscV4Metadata | ||
| 29 | -from torchtitan_npu.override.deepseek_v4.sparse_attn import asc_legacy | ||
| 30 | -from torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc import AscCompressedSparseInnerAttention | ||
| 31 | -from torchtitan_npu.patches.torchtitan.models.common.attention_metadata import cp_shard_context_set | ||
| 32 | - | ||
| 33 | -pytestmark = pytest.mark.usefixtures("dsv4") | ||
| 34 | - | ||
| 35 | -_DIM, _HEADS, _HEAD_DIM = 32, 4, 8 | ||
| 36 | -_INDEX_N_HEADS, _INDEX_HEAD_DIM, _INDEX_TOPK, _WINDOW = 2, 8, 16, 128 | ||
| 37 | - | ||
| 38 | - | ||
| 39 | -def _positions_for(doc_lens) -> torch.Tensor: | ||
| 40 | - return torch.cat([torch.arange(length) for length in doc_lens]) | ||
| 41 | - | ||
| 42 | - | ||
| 43 | -def _model_config(ratios: tuple[int, ...], *, ascendc: bool, geometry: dict | None = None): | ||
| 44 | - config = _make_v4_config( | ||
| 45 | - dim=_DIM, | ||
| 46 | - n_layers=len(ratios), | ||
| 47 | - vocab_size=64, | ||
| 48 | - n_heads=_HEADS, | ||
| 49 | - head_dim=_HEAD_DIM, | ||
| 50 | - rope_head_dim=4, | ||
| 51 | - q_lora_rank=16, | ||
| 52 | - o_lora_rank=8, | ||
| 53 | - n_groups=2, | ||
| 54 | - compress_ratios=ratios, | ||
| 55 | - window_size=_WINDOW, | ||
| 56 | - norm_eps=1e-6, | ||
| 57 | - index_n_heads=_INDEX_N_HEADS, | ||
| 58 | - index_head_dim=_INDEX_HEAD_DIM, | ||
| 59 | - index_topk=_INDEX_TOPK, | ||
| 60 | - moe_inter_dim=16, | ||
| 61 | - num_experts=2, | ||
| 62 | - num_shared_experts=1, | ||
| 63 | - top_k=1, | ||
| 64 | - n_hash_layers=0, | ||
| 65 | - route_norm=False, | ||
| 66 | - route_scale=1.0, | ||
| 67 | - load_balance_coeff=1e-3, | ||
| 68 | - hc_mult=2, | ||
| 69 | - sinkhorn_iters=2, | ||
| 70 | - hc_eps=1e-6, | ||
| 71 | - max_seq_len=_WINDOW * 2, | ||
| 72 | - compress_rope_theta=10000.0, | ||
| 73 | - original_seq_len=_WINDOW * 2, | ||
| 74 | - num_mtp_layers=0, | ||
| 75 | - ) | ||
| 76 | - # These tests exercise the explicitly retained geometry/carry backend. | ||
| 77 | - config = with_npu_attention_backend(config) | ||
| 78 | - # The sharding pass runs at config resolution, before the overrides. | ||
| 79 | - set_deepseek_v4_sharding_config(config, enable_sp=False, enable_ep=False) | ||
| 80 | - if ascendc: | ||
| 81 | - for _, inner, parent, attr in list(config.traverse(CompressedSparseInnerAttention.Config)): | ||
| 82 | - setattr( | ||
| 83 | - parent, | ||
| 84 | - attr, | ||
| 85 | - asc_legacy( | ||
| 86 | - inner, | ||
| 87 | - **( | ||
| 88 | - geometry | ||
| 89 | - or { | ||
| 90 | - "num_heads": _HEADS, | ||
| 91 | - "head_dim": _HEAD_DIM, | ||
| 92 | - "index_num_heads": _INDEX_N_HEADS, | ||
| 93 | - "index_head_dim": _INDEX_HEAD_DIM, | ||
| 94 | - } | ||
| 95 | - ), | ||
| 96 | - ), | ||
| 97 | - ) | ||
| 98 | - return config | ||
| 99 | - | ||
| 100 | - | ||
| 101 | -def _entry(model, ratio: int = 4, positions=None): | ||
| 102 | - metadata = model._get_attention_metadata(_positions_for((_WINDOW, _WINDOW)) if positions is None else positions) | ||
| 103 | - matches = [entry for entry in metadata.values() if entry.ratio == ratio] | ||
| 104 | - assert len(matches) == 1 | ||
| 105 | - return matches[0] | ||
| 106 | - | ||
| 107 | - | ||
| 108 | -def test_native_model_rejects_cp_even_with_aligned_documents(): | ||
| 109 | - from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_debugmodel | ||
| 110 | - | ||
| 111 | - config = deepseek_v4_debugmodel() | ||
| 112 | - config.parallelism.context_parallel_degree = 2 | ||
| 113 | - config.dataloader.dataset.dataset.processor.per_doc_alignment = 256 | ||
| 114 | - | ||
| 115 | - with pytest.raises(NotImplementedError, match="TP=CP=PP=1"): | ||
| 116 | - with torch.device("meta"): | ||
| 117 | - model = config.model.build() | ||
| 118 | - model.parallelize(parallelism=config.parallelism) | ||
| 119 | - | ||
| 120 | - | ||
| 121 | -def test_entries_are_built_per_geometry(): | ||
| 122 | - """One entry per (backend class, ratio), and every layer dispatches by its own key.""" | ||
| 123 | - model = _model_config((1, 1, 4, 128), ascendc=False).build() | ||
| 124 | - | ||
| 125 | - metadata = model._get_attention_metadata(_positions_for((128, 128))) | ||
| 126 | - | ||
| 127 | - assert {ratio for _, ratio in metadata} == {1, 4, 128} | ||
| 128 | - entry = metadata[(CompressedSparseInnerAttention.Config, 4)] | ||
| 129 | - assert type(entry) is DeepSeekV4Metadata and entry.ratio == 4 | ||
| 130 | - # The row grid lives on the sliding-window frame; the pool grid is this entry's own fold of it, | ||
| 131 | - # and an unpooled geometry has no pool at all. At one degree nothing is moved or restored. | ||
| 132 | - assert entry.swa_k.cu_seqlens.tolist() == [0, 128, 256] | ||
| 133 | - assert entry.cmp_k is not None and entry.cmp_k.cu_seqlens.tolist() == [0, 32, 64] | ||
| 134 | - assert metadata[(CompressedSparseInnerAttention.Config, 1)].cmp_k is None | ||
| 135 | - assert entry.cp is None | ||
| 136 | - keys = {layer.attention.attention_metadata_key for layer in model.layers.values()} | ||
| 137 | - assert {key[1] for key in keys} == {1, 4, 128} | ||
| 138 | - assert all(metadata[key].ratio == key[1] for key in keys) | ||
| 139 | - | ||
| 140 | - | ||
| 141 | -@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) | ||
| 142 | -def test_attention_without_cp_matches_independent_samples(batch_size, monkeypatch): | ||
| 143 | - """No-CP attention must preserve independent document rows and their gradients. | ||
| 144 | - | ||
| 145 | - The folded row packs what used to be batch samples as documents, so the | ||
| 146 | - oracle applies the same initialized layer to each document separately. | ||
| 147 | - """ | ||
| 148 | - seq_len = 8 | ||
| 149 | - with torch.random.fork_rng(devices=[]): | ||
| 150 | - torch.manual_seed(42) | ||
| 151 | - model = _model_config((1,), ascendc=True).build() | ||
| 152 | - attention = model.layers["0"].attention | ||
| 153 | - attention.init_states(buffer_device=torch.device("cpu")) | ||
| 154 | - | ||
| 155 | - def cpu_window_attention(q, swa_k, attn_sink, *, attention_metadata, **kwargs): | ||
| 156 | - # The fused kernel is unavailable on CPU, while attn-gym's packed reference | ||
| 157 | - # addresses one row. Isolate only that kernel with per-document dense | ||
| 158 | - # causal math; RoPE and all input/output projections remain production code. | ||
| 159 | - del kwargs | ||
| 160 | - assert attention_metadata.cp is None | ||
| 161 | - cu = attention_metadata.q.cu_seqlens.to(torch.long).tolist() | ||
| 162 | - total = q.size(0) | ||
| 163 | - scores = torch.einsum("thd,sd->ths", q.float(), swa_k.float()) * attention.inner_attention.softmax_scale | ||
| 164 | - allow = torch.zeros(total, total, dtype=torch.bool) | ||
| 165 | - for start, end in pairwise(cu): | ||
| 166 | - allow[start:end, start:end] = torch.ones(end - start, end - start, dtype=torch.bool).tril() | ||
| 167 | - scores = scores.masked_fill(~allow[:, None, :], float("-inf")) | ||
| 168 | - sink = attn_sink[None, :, None].expand(*scores.shape[:-1], 1) | ||
| 169 | - probabilities = torch.cat((scores, sink), dim=-1).softmax(dim=-1)[..., :-1] | ||
| 170 | - return torch.einsum("ths,sd->thd", probabilities, swa_k) | ||
| 171 | - | ||
| 172 | - monkeypatch.setattr(attention.inner_attention, "forward", cpu_window_attention) | ||
| 173 | - values = torch.linspace(-1.0, 1.0, batch_size * seq_len * _DIM).reshape(batch_size * seq_len, _DIM) | ||
| 174 | - x = values.clone().requires_grad_() | ||
| 175 | - positions = _positions_for((seq_len,) * batch_size) | ||
| 176 | - entry = model._get_attention_metadata(positions)[attention.attention_metadata_key] | ||
| 177 | - # The folded row is one packed row: ``batch_size`` is its own count, not the | ||
| 178 | - # number of documents that were packed into it. | ||
| 179 | - assert entry.batch_size == 1 | ||
| 180 | - # At one degree the query frame is the row's own grid and every document is a | ||
| 181 | - # batch sample here; the KV frame addresses that same row. | ||
| 182 | - assert entry.q.cu_seqlens.tolist() == [row * seq_len for row in range(batch_size + 1)] | ||
| 183 | - assert entry.swa_k.cu_seqlens.tolist() == entry.q.cu_seqlens.tolist() | ||
| 184 | - parameters = tuple(attention.parameters()) | ||
| 185 | - upstream = torch.linspace(0.25, 1.25, x.numel()).reshape_as(x) | ||
| 186 | - | ||
| 187 | - output = attention(x, entry, positions) | ||
| 188 | - assert output.shape == (batch_size * seq_len, _DIM) | ||
| 189 | - gradients = torch.autograd.grad((output * upstream).sum(), (x, *parameters)) | ||
| 190 | - | ||
| 191 | - # Distinct documents have no cross-row attention. Applying the same initialized | ||
| 192 | - # layer to each document separately supplies the batch-composition oracle, including | ||
| 193 | - # the sum of the individual parameter gradients for the same scalar objective. | ||
| 194 | - expected_outputs, expected_input_gradients = [], [] | ||
| 195 | - expected_parameter_gradients = [torch.zeros_like(parameter) for parameter in parameters] | ||
| 196 | - for row in range(batch_size): | ||
| 197 | - slab = slice(row * seq_len, (row + 1) * seq_len) | ||
| 198 | - sample = values[slab].clone().requires_grad_() | ||
| 199 | - sample_positions = _positions_for((seq_len,)) | ||
| 200 | - sample_entry = model._get_attention_metadata(sample_positions)[attention.attention_metadata_key] | ||
| 201 | - expected = attention(sample, sample_entry, sample_positions) | ||
| 202 | - sample_gradients = torch.autograd.grad((expected * upstream[slab]).sum(), (sample, *parameters)) | ||
| 203 | - expected_outputs.append(expected) | ||
| 204 | - expected_input_gradients.append(sample_gradients[0]) | ||
| 205 | - for accumulated, gradient in zip(expected_parameter_gradients, sample_gradients[1:], strict=True): | ||
| 206 | - accumulated.add_(gradient) | ||
| 207 | - | ||
| 208 | - torch.testing.assert_close(output, torch.cat(expected_outputs), rtol=1e-5, atol=1e-6) | ||
| 209 | - torch.testing.assert_close(gradients[0], torch.cat(expected_input_gradients), rtol=1e-5, atol=1e-6) | ||
| 210 | - for actual, expected in zip(gradients[1:], expected_parameter_gradients, strict=True): | ||
| 211 | - torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) | ||
| 212 | - | ||
| 213 | - | ||
| 214 | -def test_the_fused_entry_carries_its_geometry_and_records(dsv4): | ||
| 215 | - """The fused core's config builds the packed contract and its kernel records.""" | ||
| 216 | - dsv4.cann_ops.calls.clear() | ||
| 217 | - model = _model_config((1, 4, 128), ascendc=True).build() | ||
| 218 | - | ||
| 219 | - metadata = model._get_attention_metadata(_positions_for((128, 128, 128, 128))) | ||
| 220 | - | ||
| 221 | - geometry = AicpuGeometry( | ||
| 222 | - num_heads=_HEADS, | ||
| 223 | - head_dim=_HEAD_DIM, | ||
| 224 | - window_size=_WINDOW, | ||
| 225 | - index_topk=_INDEX_TOPK, | ||
| 226 | - index_num_heads=_INDEX_N_HEADS, | ||
| 227 | - index_head_dim=_INDEX_HEAD_DIM, | ||
| 228 | - ) | ||
| 229 | - for (cls, ratio), entry in metadata.items(): | ||
| 230 | - assert cls is AscCompressedSparseInnerAttention.Config and entry.ratio == ratio | ||
| 231 | - assert isinstance(entry, AscV4Metadata) | ||
| 232 | - assert entry.aicpu_metadata.geometry == geometry | ||
| 233 | - assert entry.aicpu_metadata.sparse_attn.fwd is not None | ||
| 234 | - assert entry.aicpu_metadata.sparse_attn.bwd is not None | ||
| 235 | - assert entry.q is not None and entry.swa_k is not None | ||
| 236 | - assert entry.cmp_k is None if ratio == 1 else entry.cmp_k is not None | ||
| 237 | - # The fused core never reads ``slots``: its builder skips the reference-only | ||
| 238 | - # S x (S / ratio) HCA matrix even for the ratio-128 geometry. | ||
| 239 | - assert entry.slots is None | ||
| 240 | - if ratio == 4: | ||
| 241 | - assert entry.aicpu_metadata.lightning_indexer.fwd is not None | ||
| 242 | - else: | ||
| 243 | - assert entry.aicpu_metadata.lightning_indexer.fwd is None | ||
| 244 | - smla = [call for call in dsv4.cann_ops.calls if call[0] == "sparse_flash_mla_metadata"] | ||
| 245 | - assert len(smla) == 3 | ||
| 246 | - assert {call[2]["cmp_ratio"] for call in smla} == {1, 4, 128} | ||
| 247 | - | ||
| 248 | - | ||
| 249 | -def test_only_the_reference_builds_the_hca_selection(): | ||
| 250 | - """``slots`` is the reference core's precomputed selection, not the fused core's. | ||
| 251 | - | ||
| 252 | - The reference forward reads it (``kv_indices`` for a geometry without a selector); the | ||
| 253 | - fused core's HCA branch runs full-causal on the compressed pool and never touches it, so | ||
| 254 | - its builder passes ``build_slots=False`` and the ``S x (S / ratio)`` int64 matrix -- 64 GiB | ||
| 255 | - at S=1M, ratio=128 -- is never materialised on the fused path. | ||
| 256 | - """ | ||
| 257 | - positions = _positions_for((128, 128)) | ||
| 258 | - reference = _entry(_model_config((128,), ascendc=False).build(), 128, positions) | ||
| 259 | - assert reference.slots is not None | ||
| 260 | - assert reference.slots.shape == (1, 256, 2) | ||
| 261 | - | ||
| 262 | - fused = _entry(_model_config((128,), ascendc=True).build(), 128, positions) | ||
| 263 | - assert fused.slots is None | ||
| 264 | - | ||
| 265 | - | ||
| 266 | -class _FakeCPMesh: | ||
| 267 | - """The 1-D mesh contract the metadata's CP transform reads.""" | ||
| 268 | - | ||
| 269 | - ndim = 1 | ||
| 270 | - device_type = "cpu" | ||
| 271 | - | ||
| 272 | - def __init__(self, rank: int, world_size: int): | ||
| 273 | - self._rank = rank | ||
| 274 | - self._world_size = world_size | ||
| 275 | - | ||
| 276 | - def size(self, dim: int | None = None) -> int: | ||
| 277 | - return self._world_size | ||
| 278 | - | ||
| 279 | - def get_local_rank(self) -> int: | ||
| 280 | - return self._rank | ||
| 281 | - | ||
| 282 | - | ||
| 283 | -def _prepare_for_rank(attention_metadata, positions, *, rank: int, cp_size: int = 2): | ||
| 284 | - with cp_shard_context_set( | ||
| 285 | - cp_mesh=_FakeCPMesh(rank, cp_size), | ||
| 286 | - load_balancer_type=DOC_CHUNK_LAYOUT, | ||
| 287 | - positions=positions, | ||
| 288 | - ): | ||
| 289 | - return type(attention_metadata).prepare_cp_metadata(attention_metadata, permutation=None) | ||
| 290 | - | ||
| 291 | - | ||
| 292 | -def _prefix(lengths: torch.Tensor) -> torch.Tensor: | ||
| 293 | - """The frame of a per-document prefix: the running sum of the reach, from zero.""" | ||
| 294 | - return torch.cat([torch.zeros(1, dtype=torch.int32), torch.cumsum(lengths, 0).to(torch.int32)]) | ||
| 295 | - | ||
| 296 | - | ||
| 297 | -def test_the_fused_cp_transform_rebuilds_rank_local_frames(dsv4, monkeypatch): | ||
| 298 | - """The CP half rebuilds this rank's frames and records from the global row.""" | ||
| 299 | - from torchtitan_npu.override.deepseek_v4.sparse_attn import ascendc | ||
| 300 | - | ||
| 301 | - built: list[torch.Tensor] = [] | ||
| 302 | - | ||
| 303 | - def recording_smla_metadata(*args, **kwargs): | ||
| 304 | - built.append(kwargs["cu_seqlens_q"]) | ||
| 305 | - return torch.tensor([kwargs["cu_seqlens_q"][-1].item()], dtype=torch.int32) | ||
| 306 | - | ||
| 307 | - monkeypatch.setattr(ascendc, "sparse_flash_mla_metadata", recording_smla_metadata) | ||
| 308 | - positions = _positions_for((_WINDOW, _WINDOW // 2)) | ||
| 309 | - model = _model_config((1, 4), ascendc=True).build() | ||
| 310 | - | ||
| 311 | - global_metadata = _entry(model, 4, positions) | ||
| 312 | - row = torch.tensor([0, _WINDOW, _WINDOW + _WINDOW // 2], dtype=torch.int32) | ||
| 313 | - chunk = torch.diff(row) // 2 | ||
| 314 | - | ||
| 315 | - rank_metadata = [_prepare_for_rank(global_metadata, positions, rank=rank) for rank in range(2)] | ||
| 316 | - for rank, metadata in enumerate(rank_metadata): | ||
| 317 | - # The row stays the whole row; the queries are this rank's chunks. | ||
| 318 | - _prefix_of_reach = _prefix((rank + 1) * chunk) | ||
| 319 | - assert metadata.cmp_k is not None | ||
| 320 | - assert torch.equal(metadata.q.cu_seqlens, (row // 2).to(torch.int32)) | ||
| 321 | - assert torch.equal(metadata.q.seqused, chunk) | ||
| 322 | - # The key frames are the ones the kernels read: the row itself where they honour | ||
| 323 | - # ``seqused``, the reach where they anchor their mask at the frame's end. | ||
| 324 | - expected_window = row if _IS_A5 else _prefix_of_reach | ||
| 325 | - assert torch.equal(metadata.swa_k.cu_seqlens, expected_window) | ||
| 326 | - assert torch.equal(metadata.swa_k.seqused, (rank + 1) * chunk) | ||
| 327 | - expected_pool = (row // 4).to(torch.int32) if _IS_A5 else _prefix_of_reach // 4 | ||
| 328 | - assert torch.equal(metadata.cmp_k.cu_seqlens, expected_pool) | ||
| 329 | - assert torch.equal(metadata.cmp_k.seqused, ((rank + 1) * chunk) // 4) | ||
| 330 | - assert metadata.ratio == 4 | ||
| 331 | - assert metadata.aicpu_metadata.sparse_attn.fwd is not global_metadata.aicpu_metadata.sparse_attn.fwd | ||
| 332 | - assert metadata.aicpu_metadata.geometry == global_metadata.aicpu_metadata.geometry | ||
| 333 | - assert metadata.cp is not None and metadata.cp.restore.exchange is not None | ||
| 334 | - # The restore is rank-dependent even though the row is. | ||
| 335 | - assert rank_metadata[0].position_k.tolist() != rank_metadata[1].position_k.tolist() | ||
| 336 | - | ||
| 337 | - | ||
| 338 | -def test_the_inner_attention_and_selector_own_the_cp_boundary(): | ||
| 339 | - """The core gathers its KV streams; the selector gathers the index keys it scores. | ||
| 340 | - | ||
| 341 | - Both conversions are the V4.1 ``S(1) -> R`` pattern, declared by the modules the layer | ||
| 342 | - calls directly (there is no wrapper between them any more). | ||
| 343 | - """ | ||
| 344 | - config = _model_config((4,), ascendc=True) | ||
| 345 | - attention = config.layers[0].attention | ||
| 346 | - core_sharding = attention.inner_attention.sharding_config | ||
| 347 | - assert core_sharding is not None | ||
| 348 | - names = set(core_sharding.in_src_shardings) | ||
| 349 | - assert not names & {"idx_q", "idx_k", "idx_w"} | ||
| 350 | - assert {"q", "swa_k", "cmp_k", "topk_indices", "topk_scores", "attn_sink"} <= names | ||
| 351 | - # Positional forward args are (q, swa_k, attn_sink): the KV streams are gathered on the | ||
| 352 | - # way in, so their destination placement is the whole row. | ||
| 353 | - core_row = core_sharding.in_dst_shardings | ||
| 354 | - assert core_row["swa_k"] != core_sharding.in_src_shardings["swa_k"] | ||
| 355 | - assert core_row["cmp_k"] != core_sharding.in_src_shardings["cmp_k"] | ||
| 356 | - | ||
| 357 | - selector_sharding = attention.lightning_indexer.sharding_config | ||
| 358 | - assert selector_sharding is not None | ||
| 359 | - assert set(selector_sharding.in_src_shardings) == {"idx_q", "idx_k", "idx_w"} | ||
| 360 | - assert selector_sharding.in_dst_shardings["idx_k"] != selector_sharding.in_src_shardings["idx_k"] | ||
| @@ -1,429 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | -# | ||
| 3 | -# This source code is licensed under the BSD-style license found in the | ||
| 4 | -# LICENSE file in the root directory of this source tree. | ||
| 5 | - | ||
| 6 | -"""CPU oracle at the CANN boundary, with real configs and document metadata. | ||
| 7 | - | ||
| 8 | -The fused compressor is CP-agnostic: it compresses the local stream it is handed, addressed by | ||
| 9 | -that stream's own ``cu_seqlens``. Under context parallelism the ratio-4 overlap's carry is | ||
| 10 | -``CarryExchange``'s job, so the CP cases here compose the exchange with the same kernel module | ||
| 11 | -and compare each rank's kept blocks with the whole row's pool. | ||
| 12 | -""" | ||
| 13 | - | ||
| 14 | -import copy | ||
| 15 | -import importlib | ||
| 16 | -import sys | ||
| 17 | -import types | ||
| 18 | -from itertools import pairwise | ||
| 19 | - | ||
| 20 | -import pytest | ||
| 21 | -import torch | ||
| 22 | -import torch.nn.functional as F | ||
| 23 | -from torchtitan.config import OverrideConfig, apply_overrides | ||
| 24 | - | ||
| 25 | -from torchtitan_npu.models.common.carry_exchange import CarryExchange | ||
| 26 | -from torchtitan_npu.models.deepseek_v4 import _debugmodel as _native_debugmodel | ||
| 27 | -from torchtitan_npu.models.deepseek_v4 import _make_v4_config | ||
| 28 | -from torchtitan_npu.models.deepseek_v4.backend import with_npu_attention_backend | ||
| 29 | -from torchtitan_npu.models.deepseek_v4.compressor import ( | ||
| 30 | - Compressor, | ||
| 31 | - CompressorImplementation, | ||
| 32 | -) | ||
| 33 | -from torchtitan_npu.models.deepseek_v4.metadata import build_v4_metadata | ||
| 34 | -from torchtitan_npu.models.deepseek_v4.sharding import set_deepseek_v4_sharding_config | ||
| 35 | -from torchtitan_npu.override.deepseek_v4.compressor import ascendc | ||
| 36 | -from torchtitan_npu.override.deepseek_v4.metadata import AicpuGeometry | ||
| 37 | -from torchtitan_npu.override.deepseek_v4.sparse_attn.ascendc import build_aicpu_metadata | ||
| 38 | - | ||
| 39 | -_FUSED_GEOMETRY = AicpuGeometry( | ||
| 40 | - num_heads=16, | ||
| 41 | - head_dim=512, | ||
| 42 | - window_size=8, | ||
| 43 | - index_topk=16, | ||
| 44 | - index_num_heads=8, | ||
| 45 | - index_head_dim=128, | ||
| 46 | -) | ||
| 47 | - | ||
| 48 | - | ||
| 49 | -def _debugmodel(): | ||
| 50 | - return with_npu_attention_backend(_native_debugmodel()) | ||
| 51 | - | ||
| 52 | - | ||
| 53 | -def _positions(cu: torch.Tensor) -> torch.Tensor: | ||
| 54 | - """A packed row's document-relative positions, from its boundaries.""" | ||
| 55 | - return torch.cat([torch.arange(end - start) for start, end in pairwise(cu.tolist())]) | ||
| 56 | - | ||
| 57 | - | ||
| 58 | -def _entry(cu: torch.Tensor, ratio: int): | ||
| 59 | - """One geometry's model entry: the row and this ratio's fold of it.""" | ||
| 60 | - return build_v4_metadata(_positions(cu), ratio, cu_seq_q=cu) | ||
| 61 | - | ||
| 62 | - | ||
| 63 | -def _fused_entry(cu: torch.Tensor, ratio: int = 4): | ||
| 64 | - """One geometry's fused entry: the model entry plus its records.""" | ||
| 65 | - return build_aicpu_metadata(_entry(cu, ratio), geometry=_FUSED_GEOMETRY) | ||
| 66 | - | ||
| 67 | - | ||
| 68 | -def _tiny_config(): | ||
| 69 | - """A two-layer stack with one compressed (ratio-4) layer, cheap to build.""" | ||
| 70 | - config = _make_v4_config( | ||
| 71 | - dim=32, | ||
| 72 | - n_layers=2, | ||
| 73 | - vocab_size=64, | ||
| 74 | - n_heads=4, | ||
| 75 | - head_dim=8, | ||
| 76 | - rope_head_dim=4, | ||
| 77 | - q_lora_rank=16, | ||
| 78 | - o_lora_rank=8, | ||
| 79 | - n_groups=2, | ||
| 80 | - compress_ratios=(1, 4), | ||
| 81 | - window_size=128, | ||
| 82 | - norm_eps=1e-6, | ||
| 83 | - index_n_heads=2, | ||
| 84 | - index_head_dim=8, | ||
| 85 | - index_topk=16, | ||
| 86 | - moe_inter_dim=16, | ||
| 87 | - num_experts=2, | ||
| 88 | - num_shared_experts=1, | ||
| 89 | - top_k=1, | ||
| 90 | - n_hash_layers=0, | ||
| 91 | - route_norm=False, | ||
| 92 | - route_scale=1.0, | ||
| 93 | - load_balance_coeff=1e-3, | ||
| 94 | - hc_mult=2, | ||
| 95 | - sinkhorn_iters=2, | ||
| 96 | - hc_eps=1e-6, | ||
| 97 | - max_seq_len=256, | ||
| 98 | - compress_rope_theta=10000.0, | ||
| 99 | - original_seq_len=256, | ||
| 100 | - ) | ||
| 101 | - # The sharding pass runs at config resolution, before the overrides. | ||
| 102 | - config = with_npu_attention_backend(config) | ||
| 103 | - set_deepseek_v4_sharding_config(config, enable_sp=False, enable_ep=False) | ||
| 104 | - return config | ||
| 105 | - | ||
| 106 | - | ||
| 107 | -@pytest.mark.parametrize("reverse", [False, True], ids=["compressor-first", "compressor-last"]) | ||
| 108 | -def test_compressor_override_composes_with_norm_and_rope(monkeypatch, reverse): | ||
| 109 | - from torchtitan_npu.override.common.rms_norm import AscRMSNorm | ||
| 110 | - from torchtitan_npu.override.common.rope import AscComplexRoPE | ||
| 111 | - | ||
| 112 | - registry = importlib.import_module("torchtitan.config.override") | ||
| 113 | - monkeypatch.setattr(registry, "_REGISTRY", registry._REGISTRY.copy()) | ||
| 114 | - cfg = _debugmodel() | ||
| 115 | - imports = [ | ||
| 116 | - "torchtitan_npu.override.deepseek_v4.compressor.legacy_asc", | ||
| 117 | - "torchtitan_npu.override.common.rms_norm.asc", | ||
| 118 | - "torchtitan_npu.override.common.rope.asc_complex", | ||
| 119 | - ] | ||
| 120 | - apply_overrides(OverrideConfig(imports=imports[::-1] if reverse else imports), cfg) | ||
| 121 | - compressors = [node for _, node, _, _ in cfg.traverse(Compressor.Config)] | ||
| 122 | - assert compressors | ||
| 123 | - for node in compressors: | ||
| 124 | - assert type(node) is Compressor.Config | ||
| 125 | - assert isinstance(node.implementation, ascendc.AscCompressor.Config) | ||
| 126 | - assert isinstance(node.norm, AscRMSNorm.Config) | ||
| 127 | - assert isinstance(node.rope, AscComplexRoPE.Config) | ||
| 128 | - assert all( | ||
| 129 | - type(node.implementation) is CompressorImplementation.Config | ||
| 130 | - for _, node, _, _ in _debugmodel().traverse(Compressor.Config) | ||
| 131 | - ) | ||
| 132 | - | ||
| 133 | - | ||
| 134 | -def _document_pool(x, wkv, wgate, ape, cu, ratio): | ||
| 135 | - outputs = [] | ||
| 136 | - width = wkv.shape[0] // (2 if ratio == 4 else 1) | ||
| 137 | - for start, end in pairwise(cu): | ||
| 138 | - values = F.linear(x[start:end].float(), wkv.float()) | ||
| 139 | - scores = F.linear(x[start:end].float(), wgate.float()) | ||
| 140 | - for offset in range(0, (end - start) // ratio * ratio, ratio): | ||
| 141 | - current_values = values[offset : offset + ratio, -width:] | ||
| 142 | - current_scores = scores[offset : offset + ratio, -width:] + ape[:, -width:] | ||
| 143 | - if ratio == 4 and offset: | ||
| 144 | - current_values = torch.cat((values[offset - ratio : offset, :width], current_values)) | ||
| 145 | - current_scores = torch.cat((scores[offset - ratio : offset, :width] + ape[:, :width], current_scores)) | ||
| 146 | - outputs.append((current_values * current_scores.softmax(0)).sum(0)) | ||
| 147 | - return torch.stack(outputs) | ||
| 148 | - | ||
| 149 | - | ||
| 150 | -def _postprocess(module, pooled, positions): | ||
| 151 | - normalized = F.rms_norm(pooled, (module.head_dim,), module.norm.weight, module.norm.eps) | ||
| 152 | - return module.rope(normalized[:, None, :], positions=positions)[:, 0, :] | ||
| 153 | - | ||
| 154 | - | ||
| 155 | -@pytest.fixture | ||
| 156 | -def compressor_factory(monkeypatch): | ||
| 157 | - registry = importlib.import_module("torchtitan.config.override") | ||
| 158 | - with monkeypatch.context() as scoped, torch.random.fork_rng(devices=[]): | ||
| 159 | - scoped.setattr(registry, "_REGISTRY", registry._REGISTRY.copy()) | ||
| 160 | - fake_module = types.ModuleType("compressor") | ||
| 161 | - fake_module.compressor = lambda *args, **kwargs: pytest.fail("unexpected CANN compressor call") | ||
| 162 | - scoped.setitem(sys.modules, "cann_ops_transformer.ops.compressor", fake_module) | ||
| 163 | - torch.manual_seed(93) | ||
| 164 | - | ||
| 165 | - def build(ratio, indexer=False): | ||
| 166 | - cfg = _debugmodel() | ||
| 167 | - apply_overrides(OverrideConfig(imports=["torchtitan_npu.override.deepseek_v4.compressor.legacy_asc"]), cfg) | ||
| 168 | - attention = cfg.layers[2 if ratio == 4 else 3].attention | ||
| 169 | - compressor_cfg = attention.indexer.compressor if indexer else attention.compressor | ||
| 170 | - compressor_cfg.wkv.in_features = 1024 | ||
| 171 | - compressor_cfg.wgate.in_features = 1024 | ||
| 172 | - module = compressor_cfg.build() | ||
| 173 | - assert isinstance(module.implementation, ascendc.AscCompressor) | ||
| 174 | - module.init_states(buffer_device=torch.device("cpu")) | ||
| 175 | - module.wkv.to(torch.float16) | ||
| 176 | - module.wgate.to(torch.float16) | ||
| 177 | - module.norm.to(torch.float16) | ||
| 178 | - return module | ||
| 179 | - | ||
| 180 | - try: | ||
| 181 | - yield build | ||
| 182 | - finally: | ||
| 183 | - torch._dynamo.reset() | ||
| 184 | - | ||
| 185 | - | ||
| 186 | -@pytest.mark.parametrize( | ||
| 187 | - "ratio,indexer", [(4, False), (4, True), (128, False)], ids=["c4-attention", "c4-indexer", "c128"] | ||
| 188 | -) | ||
| 189 | -@pytest.mark.parametrize("api", ["torch-op", "python-wrapper"]) | ||
| 190 | -@pytest.mark.parametrize("ape_dtype", [torch.float32, torch.bfloat16]) | ||
| 191 | -@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) | ||
| 192 | -def test_compressor_cann_schema_document_outputs_and_gradients( | ||
| 193 | - compressor_factory, monkeypatch, ratio, indexer, api, ape_dtype, batch_size | ||
| 194 | -): | ||
| 195 | - calls = [] | ||
| 196 | - lengths = [2 * ratio, ratio, 2 * ratio] * batch_size | ||
| 197 | - | ||
| 198 | - def fake_cann( | ||
| 199 | - x, | ||
| 200 | - wkv, | ||
| 201 | - wgate, | ||
| 202 | - state_cache, | ||
| 203 | - ape, | ||
| 204 | - cmp_ratio=4, | ||
| 205 | - *, | ||
| 206 | - state_block_table=None, | ||
| 207 | - cu_seqlens=None, | ||
| 208 | - seqused=None, | ||
| 209 | - start_pos=None, | ||
| 210 | - coff=1, | ||
| 211 | - cache_mode=1, | ||
| 212 | - ): | ||
| 213 | - assert torch.is_grad_enabled() | ||
| 214 | - calls.append(cmp_ratio) | ||
| 215 | - assert x.dtype == wkv.dtype == wgate.dtype == torch.float16 | ||
| 216 | - assert ape.dtype == state_cache.dtype == torch.float32 | ||
| 217 | - assert x.shape[1] == wkv.shape[1] == wgate.shape[1] == 1024 | ||
| 218 | - assert wkv is module.wkv.weight and wgate is module.wgate.weight | ||
| 219 | - torch.testing.assert_close(ape, module.ape.float()) | ||
| 220 | - block_size = 8 if cmp_ratio == 4 else 16 | ||
| 221 | - assert state_cache.shape == (1, block_size, 2 * coff * module.head_dim) | ||
| 222 | - # The port builds the all-zero tiling table from the stream's own shape symbols (the | ||
| 223 | - # model-level interface never sees it); a host maximum would go stale on the next batch. | ||
| 224 | - assert state_block_table.shape[0] == len(lengths) | ||
| 225 | - assert state_block_table.shape[1] == max((sum(lengths) + block_size - 1) // block_size, 1) | ||
| 226 | - assert not state_block_table.any() and start_pos is None and cache_mode == 1 | ||
| 227 | - torch.testing.assert_close(cu_seqlens, boundaries) | ||
| 228 | - torch.testing.assert_close(seqused, torch.tensor(lengths, dtype=torch.int32)) | ||
| 229 | - pooled = (2 * _document_pool(x, wkv, wgate, ape, cu, cmp_ratio) + perturbation).to(x.dtype) | ||
| 230 | - # Poison unused TND capacity so consuming it fails output comparisons. | ||
| 231 | - return torch.cat((pooled, pooled.new_full((len(lengths), module.head_dim), float("nan")))) | ||
| 232 | - | ||
| 233 | - if api == "torch-op": | ||
| 234 | - monkeypatch.setattr( | ||
| 235 | - torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False | ||
| 236 | - ) | ||
| 237 | - else: | ||
| 238 | - monkeypatch.setattr(torch.ops, "cann_ops_transformer", types.SimpleNamespace()) | ||
| 239 | - monkeypatch.setattr(sys.modules["cann_ops_transformer.ops.compressor"], "compressor", fake_cann) | ||
| 240 | - | ||
| 241 | - module = compressor_factory(ratio, indexer) | ||
| 242 | - module.ape = torch.nn.Parameter(module.ape.detach().to(ape_dtype), requires_grad=module.ape.requires_grad) | ||
| 243 | - module.wgate.weight.requires_grad_(not indexer) | ||
| 244 | - reference = copy.deepcopy(module) | ||
| 245 | - cu = [0] | ||
| 246 | - for length in lengths: | ||
| 247 | - cu.append(cu[-1] + length) | ||
| 248 | - boundaries = torch.tensor(cu, dtype=torch.int32) | ||
| 249 | - positions = _positions(boundaries) | ||
| 250 | - metadata = _entry(boundaries, ratio) | ||
| 251 | - generator = torch.Generator().manual_seed(21) | ||
| 252 | - x = ( | ||
| 253 | - (torch.randn(cu[-1], module.wkv.in_features, generator=generator) * 0.1) | ||
| 254 | - .half() | ||
| 255 | - .requires_grad_() | ||
| 256 | - ) | ||
| 257 | - reference_x = x.detach().clone().requires_grad_() | ||
| 258 | - perturbation = torch.linspace(-0.02, 0.03, module.head_dim) | ||
| 259 | - | ||
| 260 | - actual = module(x, positions, cu_seqlens=metadata.swa_k.cu_seqlens) | ||
| 261 | - # Match the operator boundary: accumulate APE gradients in FP32, then cast | ||
| 262 | - # once back to the BF16 parameter instead of rounding each sliced contribution. | ||
| 263 | - raw = _document_pool( | ||
| 264 | - reference_x, reference.wkv.weight, reference.wgate.weight, reference.ape.float(), cu, ratio | ||
| 265 | - ) | ||
| 266 | - expected = _postprocess(reference, (2 * raw + perturbation).half(), positions[::ratio]) | ||
| 267 | - upstream_grad = torch.randn(actual.shape, generator=generator).half() | ||
| 268 | - actual.backward(upstream_grad) | ||
| 269 | - expected.backward(upstream_grad) | ||
| 270 | - | ||
| 271 | - assert calls == [ratio] | ||
| 272 | - torch.testing.assert_close(actual, expected, rtol=0, atol=0) | ||
| 273 | - torch.testing.assert_close(x.grad, reference_x.grad, rtol=0.006, atol=0.004) | ||
| 274 | - for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"): | ||
| 275 | - actual_grad = module.get_parameter(name).grad | ||
| 276 | - expected_grad = reference.get_parameter(name).grad | ||
| 277 | - if expected_grad is None: | ||
| 278 | - assert actual_grad is None | ||
| 279 | - else: | ||
| 280 | - torch.testing.assert_close(actual_grad, expected_grad, rtol=0.006, atol=0.004) | ||
| 281 | - | ||
| 282 | - | ||
| 283 | -@pytest.mark.parametrize("api", ["torch-op", "python-wrapper"]) | ||
| 284 | -@pytest.mark.parametrize("batch_size", [1, 2], ids=["batch1", "batch2"]) | ||
| 285 | -def test_compressor_available_api_compiles(compressor_factory, monkeypatch, api, batch_size): | ||
| 286 | - def fake_cann(x, wkv, wgate, state_cache, ape, cmp_ratio=4, **kwargs): | ||
| 287 | - width = wkv.shape[0] // 2 | ||
| 288 | - values = F.linear(x.float(), wkv.float()).reshape(-1, cmp_ratio, 2, width) | ||
| 289 | - scores = F.linear(x.float(), wgate.float()).reshape_as(values) + ape.reshape(1, cmp_ratio, 2, width) | ||
| 290 | - return (values[:, :, 1] * scores[:, :, 1].softmax(dim=1)).sum(dim=1).to(x.dtype) | ||
| 291 | - | ||
| 292 | - if api == "torch-op": | ||
| 293 | - monkeypatch.setattr( | ||
| 294 | - torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False | ||
| 295 | - ) | ||
| 296 | - else: | ||
| 297 | - monkeypatch.setattr(torch.ops, "cann_ops_transformer", types.SimpleNamespace()) | ||
| 298 | - monkeypatch.setattr(sys.modules["cann_ops_transformer.ops.compressor"], "compressor", fake_cann) | ||
| 299 | - module = compressor_factory(4).float() | ||
| 300 | - reference = copy.deepcopy(module) | ||
| 301 | - boundaries = torch.arange(batch_size + 1, dtype=torch.int32) * 8 | ||
| 302 | - positions = _positions(boundaries) | ||
| 303 | - metadata = _entry(boundaries, 4) | ||
| 304 | - x = torch.randn(batch_size * 8, module.wkv.in_features, generator=torch.Generator().manual_seed(17)).requires_grad_() | ||
| 305 | - reference_x = x.detach().clone().requires_grad_() | ||
| 306 | - | ||
| 307 | - actual = torch.compile(module, backend="aot_eager", fullgraph=True, dynamic=True)( | ||
| 308 | - x, positions, cu_seqlens=metadata.swa_k.cu_seqlens | ||
| 309 | - ) | ||
| 310 | - expected = reference(reference_x, positions, cu_seqlens=metadata.swa_k.cu_seqlens) | ||
| 311 | - torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) | ||
| 312 | - actual.sum().backward() | ||
| 313 | - expected.sum().backward() | ||
| 314 | - # The crossing-document fixture also changes the CP-segment / full-document GEMM | ||
| 315 | - # batch shapes, so the gradient accumulation order differs; the measured worst | ||
| 316 | - # at c128 is 1.43e-05 (2/524288 elements), still fp32 rounding noise. | ||
| 317 | - torch.testing.assert_close(x.grad, reference_x.grad, rtol=1e-4, atol=2e-5) | ||
| 318 | - for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"): | ||
| 319 | - torch.testing.assert_close( | ||
| 320 | - module.get_parameter(name).grad, reference.get_parameter(name).grad, rtol=1e-4, atol=1e-5 | ||
| 321 | - ) | ||
| 322 | - | ||
| 323 | - | ||
| 324 | -class _FakeMesh: | ||
| 325 | - """The two mesh methods the carry reads.""" | ||
| 326 | - | ||
| 327 | - def __init__(self, rank: int, size: int): | ||
| 328 | - self._rank, self._size = rank, size | ||
| 329 | - | ||
| 330 | - def get_local_rank(self) -> int: | ||
| 331 | - return self._rank | ||
| 332 | - | ||
| 333 | - def size(self) -> int: | ||
| 334 | - return self._size | ||
| 335 | - | ||
| 336 | - | ||
| 337 | -@pytest.mark.parametrize("ratio,indexer", [(4, False), (4, True)], ids=["c4-attention", "c4-indexer"]) | ||
| 338 | -def test_compressor_cp_carry_trim_matches_the_global_pool(compressor_factory, monkeypatch, ratio, indexer): | ||
| 339 | - """The exchange's keep-set is exactly this rank's block range of the whole row's pool. | ||
| 340 | - | ||
| 341 | - Two equal documents span the four slabs, so ranks 1 and 3 carry the previous rank's last | ||
| 342 | - block; rank 2's slab starts at the second document's edge and carries it as a segment of its | ||
| 343 | - own. The fake kernel is the same per-document pool the unsharded tests use, so any | ||
| 344 | - difference is the CP framing itself. | ||
| 345 | - """ | ||
| 346 | - from torchtitan_npu.models.common import carry_exchange as carry_module | ||
| 347 | - | ||
| 348 | - cp_size = 4 | ||
| 349 | - total = 16 * ratio | ||
| 350 | - cu = [0, 8 * ratio, total] | ||
| 351 | - boundaries = torch.tensor(cu, dtype=torch.int32) | ||
| 352 | - positions = _positions(boundaries) | ||
| 353 | - slab = total // cp_size | ||
| 354 | - | ||
| 355 | - module = compressor_factory(ratio, indexer).float() | ||
| 356 | - reference = copy.deepcopy(module) | ||
| 357 | - generator = torch.Generator().manual_seed(42) | ||
| 358 | - x = (torch.randn(total, module.wkv.in_features, generator=generator) * 0.1).requires_grad_() | ||
| 359 | - reference_x = x.detach().clone().requires_grad_() | ||
| 360 | - shards = x.reshape(cp_size, slab, -1) | ||
| 361 | - current = [0] | ||
| 362 | - | ||
| 363 | - def fake_all_to_all(send, *, output_split_sizes, input_split_sizes, group): | ||
| 364 | - del group | ||
| 365 | - # ``all_to_all_single`` splits dim 0, so the block travels as ``[ratio, D]`` rows. | ||
| 366 | - assert send.size(0) == sum(input_split_sizes) | ||
| 367 | - sources = [source for source, split in enumerate(output_split_sizes) if split] | ||
| 368 | - if not sources: | ||
| 369 | - return send[:0] | ||
| 370 | - assert sources == [current[0] - 1] | ||
| 371 | - source = sources[0] | ||
| 372 | - first = source * slab | ||
| 373 | - if send.dtype == torch.int32: | ||
| 374 | - return positions[..., first + slab - ratio : first + slab].reshape(-1).to(torch.int32) | ||
| 375 | - return shards[source][-ratio:] | ||
| 376 | - | ||
| 377 | - def fake_cann( | ||
| 378 | - x_flat, | ||
| 379 | - wkv, | ||
| 380 | - wgate, | ||
| 381 | - state_cache, | ||
| 382 | - ape, | ||
| 383 | - cmp_ratio=4, | ||
| 384 | - *, | ||
| 385 | - state_block_table=None, | ||
| 386 | - cu_seqlens=None, | ||
| 387 | - seqused=None, | ||
| 388 | - start_pos=None, | ||
| 389 | - coff=1, | ||
| 390 | - cache_mode=1, | ||
| 391 | - ): | ||
| 392 | - del state_cache, state_block_table, seqused, start_pos, cache_mode | ||
| 393 | - assert coff == (2 if cmp_ratio == 4 else 1) | ||
| 394 | - return _document_pool(x_flat, wkv, wgate, ape, cu_seqlens.tolist(), cmp_ratio).to(x_flat.dtype) | ||
| 395 | - | ||
| 396 | - monkeypatch.setattr(carry_module, "all_to_all_single", fake_all_to_all) | ||
| 397 | - monkeypatch.setattr(module.implementation, "_compressor_fn", fake_cann) | ||
| 398 | - | ||
| 399 | - global_raw = _document_pool(reference_x, reference.wkv.weight, reference.wgate.weight, reference.ape, cu, ratio) | ||
| 400 | - global_positions = torch.cat( | ||
| 401 | - [torch.arange(0, (end - start) // ratio * ratio, ratio) for start, end in pairwise(cu)] | ||
| 402 | - ) | ||
| 403 | - global_expected = _postprocess(reference, global_raw, global_positions) | ||
| 404 | - losses, expected_losses = [], [] | ||
| 405 | - for rank in range(cp_size): | ||
| 406 | - current[0] = rank | ||
| 407 | - exchange = CarryExchange(CarryExchange.Config(ratio=ratio)) | ||
| 408 | - exchange.group = _FakeMesh(rank, cp_size) | ||
| 409 | - carry = exchange( | ||
| 410 | - shards[rank : rank + 1], | ||
| 411 | - positions[None, rank * slab : (rank + 1) * slab], | ||
| 412 | - boundaries, | ||
| 413 | - ) | ||
| 414 | - pooled = module(carry.x.squeeze(0), carry.positions.squeeze(0), cu_seqlens=carry.cu_seqlens) | ||
| 415 | - pooled = pooled.narrow(0, carry.trim, pooled.size(0) - carry.trim) | ||
| 416 | - actual = pooled | ||
| 417 | - expected = global_expected[rank * (slab // ratio) : (rank + 1) * (slab // ratio)] | ||
| 418 | - # The CP segments and full documents use different CPU GEMM batch shapes. | ||
| 419 | - torch.testing.assert_close(actual, expected, rtol=1e-5, atol=2e-6) | ||
| 420 | - grad = torch.randn(actual.shape, generator=generator) | ||
| 421 | - losses.append((actual * grad).sum()) | ||
| 422 | - expected_losses.append((expected * grad).sum()) | ||
| 423 | - sum(losses).backward() | ||
| 424 | - sum(expected_losses).backward() | ||
| 425 | - torch.testing.assert_close(x.grad, reference_x.grad, rtol=1e-4, atol=1e-5) | ||
| 426 | - for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"): | ||
| 427 | - torch.testing.assert_close( | ||
| 428 | - module.get_parameter(name).grad, reference.get_parameter(name).grad, rtol=1e-4, atol=1e-5 | ||
| 429 | - ) | ||
| @@ -8,4 +8,5 @@ | |||
| 8 | - **目标状态:** 与 `patches` 一起自包含,只依赖标准库、上游包和本层内部模块;新增代码不得直接依赖 `extensions`、`override` 或 `ops`。 | 8 | - **目标状态:** 与 `patches` 一起自包含,只依赖标准库、上游包和本层内部模块;新增代码不得直接依赖 `extensions`、`override` 或 `ops`。 |
| 9 | - **当前债务:** DeepSeek-V4/V4.1 的配置、并行化、checkpoint 适配仍直接使用 extension 或 override,Qwen3.5 也直接使用模型专属 override。它们的收敛范围记录在架构 Agent Note,不作为新增依赖的先例。 | 9 | - **当前债务:** DeepSeek-V4/V4.1 的配置、并行化、checkpoint 适配仍直接使用 extension 或 override,Qwen3.5 也直接使用模型专属 override。它们的收敛范围记录在架构 Agent Note,不作为新增依赖的先例。 |
| 10 | - 模型需要 NPU kernel 时应经上游或 override 注入,不新增对 `ops` 的直接依赖。 | 10 | - 模型需要 NPU kernel 时应经上游或 override 注入,不新增对 `ops` 的直接依赖。 |
| 11 | +- DeepSeek-V4 使用原生模型配置,按需选择 compressor / inner-attention override;不再提供 `backend.py` 的旧版整层注意力与布局转换入口。 | ||
| 11 | - `train.py` 只导入 `torchtitan_npu` 以激活 patches 与 extensions,不导入其他 `torchtitan_npu` 子模块;真正训练入口来自上游 TorchTitan。 | 12 | - `train.py` 只导入 `torchtitan_npu` 以激活 patches 与 extensions,不导入其他 `torchtitan_npu` 子模块;真正训练入口来自上游 TorchTitan。 |
| @@ -1,156 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 2 | -# SPDX-License-Identifier: BSD-3-Clause | ||
| 3 | - | ||
| 4 | -"""Legacy NPU geometry layout for older experiments and checkpoints. | ||
| 5 | - | ||
| 6 | -Maintained V4 recipes keep upstream attention and use compressor/inner-attention | ||
| 7 | -overrides directly. These converters remain only for explicit legacy callers. | ||
| 8 | -""" | ||
| 9 | - | ||
| 10 | -from __future__ import annotations | ||
| 11 | - | ||
| 12 | -from copy import deepcopy | ||
| 13 | -from dataclasses import dataclass, replace | ||
| 14 | -from typing import TYPE_CHECKING | ||
| 15 | - | ||
| 16 | -from torchtitan.config import derive | ||
| 17 | -from torchtitan.models.common.linear import Linear | ||
| 18 | -from torchtitan.models.deepseek_v4.attention import DeepSeekV4Attention | ||
| 19 | - | ||
| 20 | -from torchtitan_npu.models.common.carry_exchange import CarryExchange | ||
| 21 | -from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear | ||
| 22 | - | ||
| 23 | -from .attention import NPUAttention, NPUCompressedSparseInnerAttention, UnitScaleRMSNorm | ||
| 24 | -from .compressor import LightningIndexer, NPUCompressor, NPUIndexer | ||
| 25 | -from .model import DeepSeekV4Model | ||
| 26 | -from .sharding import set_deepseek_v4_attention_sharding | ||
| 27 | -from .state_dict_adapter import DeepSeekV4StateDictAdapter | ||
| 28 | - | ||
| 29 | -if TYPE_CHECKING: | ||
| 30 | - from torchtitan.models.deepseek_v4.compressor import Compressor, Indexer | ||
| 31 | - | ||
| 32 | - | ||
| 33 | -class NPUBackendDeepSeekV4Model(DeepSeekV4Model): | ||
| 34 | - """Upstream V4 model/block math with the NPU attention checkpoint layout.""" | ||
| 35 | - | ||
| 36 | - state_dict_adapter_cls = DeepSeekV4StateDictAdapter | ||
| 37 | - | ||
| 38 | - @dataclass(kw_only=True, slots=True) | ||
| 39 | - class Config(DeepSeekV4Model.Config): | ||
| 40 | - pass | ||
| 41 | - | ||
| 42 | - | ||
| 43 | -def _split_rope(config, *, head_dim: int, rope_head_dim: int): | ||
| 44 | - # The package's split-aware RoPE config is installed before model loading. | ||
| 45 | - return replace(config, split=head_dim - rope_head_dim) | ||
| 46 | - | ||
| 47 | - | ||
| 48 | -def _to_npu_compressor(config: Compressor.Config) -> NPUCompressor.Config: | ||
| 49 | - return derive( | ||
| 50 | - config, | ||
| 51 | - NPUCompressor.Config, | ||
| 52 | - rope=_split_rope(config.rope, head_dim=config.head_dim, rope_head_dim=config.rope_head_dim), | ||
| 53 | - carry_exchange=CarryExchange.Config(ratio=config.compress_ratio), | ||
| 54 | - ) | ||
| 55 | - | ||
| 56 | - | ||
| 57 | -def _to_npu_indexer(config: Indexer.Config) -> NPUIndexer.Config: | ||
| 58 | - return derive( | ||
| 59 | - config, | ||
| 60 | - NPUIndexer.Config, | ||
| 61 | - rope=_split_rope(config.rope, head_dim=config.index_head_dim, rope_head_dim=config.rope_head_dim), | ||
| 62 | - compressor=_to_npu_compressor(config.compressor), | ||
| 63 | - ) | ||
| 64 | - | ||
| 65 | - | ||
| 66 | -def to_npu_attention_config( | ||
| 67 | - config: DeepSeekV4Attention.Config, | ||
| 68 | - *, | ||
| 69 | - enable_sp: bool = False, | ||
| 70 | -) -> NPUAttention.Config: | ||
| 71 | - """Translate native attention storage/metadata without mutating its config. | ||
| 72 | - | ||
| 73 | - The backend owns document geometry, carry exchange and the selector node | ||
| 74 | - consumed by the existing NPU component overrides. Its sink is a bare | ||
| 75 | - ``[heads]`` parameter; the upstream reference keeps ``[heads, 1]`` in a | ||
| 76 | - Linear module. Grouped output projection weights have the same flattened | ||
| 77 | - storage in both implementations. | ||
| 78 | - """ | ||
| 79 | - if isinstance(config, NPUAttention.Config): | ||
| 80 | - return deepcopy(config) | ||
| 81 | - if not isinstance(config, DeepSeekV4Attention.Config): | ||
| 82 | - raise TypeError(f"Expected a native DeepSeekV4Attention.Config, got {type(config).__name__}") | ||
| 83 | - if type(config.wo_a) is not Linear.Config or type(config.attn_sink) is not Linear.Config: | ||
| 84 | - raise ValueError("Select the NPU attention backend before converting output projection or sink linears") | ||
| 85 | - if config.wo_a.bias or config.wo_a.num_linears != 1 or config.attn_sink.bias: | ||
| 86 | - raise ValueError("The NPU attention backend requires the native bias-free grouped projection and sink layout") | ||
| 87 | - if config.inner_attention.aux_loss is not None: | ||
| 88 | - raise ValueError( | ||
| 89 | - "The NPU attention backend owns its indexer objective; construct the native config " | ||
| 90 | - "with indexer_loss_coeff=0 before selecting the backend." | ||
| 91 | - ) | ||
| 92 | - config = deepcopy(config) | ||
| 93 | - # Upstream denotes window-only attention by ratio 0; NPU geometry uses 1. | ||
| 94 | - compress_ratio = max(1, config.compress_ratio) | ||
| 95 | - compressor = config.compressor if config.compress_ratio == 4 else config.compressor_128 | ||
| 96 | - if config.compress_ratio > 1 and compressor is None: | ||
| 97 | - raise ValueError(f"Compression ratio {config.compress_ratio} requires its compressor config") | ||
| 98 | - if config.wo_a.out_features % config.n_groups: | ||
| 99 | - raise ValueError("The grouped output projection width must be divisible by n_groups") | ||
| 100 | - sink_init = (config.attn_sink.param_init or {}).get("weight") | ||
| 101 | - param_init = dict(config.param_init or {}) | ||
| 102 | - if sink_init is not None: | ||
| 103 | - param_init["attn_sink"] = sink_init | ||
| 104 | - result = NPUAttention.Config( | ||
| 105 | - n_heads=config.n_heads, | ||
| 106 | - head_dim=config.head_dim, | ||
| 107 | - rope_head_dim=config.rope_head_dim, | ||
| 108 | - q_lora_rank=config.q_lora_rank, | ||
| 109 | - n_groups=config.n_groups, | ||
| 110 | - compress_ratio=compress_ratio, | ||
| 111 | - norm_eps=config.norm_eps, | ||
| 112 | - rope=_split_rope(config.rope, head_dim=config.head_dim, rope_head_dim=config.rope_head_dim), | ||
| 113 | - wq_a=config.wq_a, | ||
| 114 | - q_norm=config.q_norm, | ||
| 115 | - q_head_norm=UnitScaleRMSNorm.Config(normalized_shape=config.head_dim, eps=config.norm_eps), | ||
| 116 | - wq_b=config.wq_b, | ||
| 117 | - wkv=config.wkv, | ||
| 118 | - kv_norm=config.kv_norm, | ||
| 119 | - wo_a=BatchedLinear.Config( | ||
| 120 | - n_heads=config.n_groups, | ||
| 121 | - in_features=config.wo_a.in_features, | ||
| 122 | - out_features=config.wo_a.out_features // config.n_groups, | ||
| 123 | - param_init=config.wo_a.param_init, | ||
| 124 | - ), | ||
| 125 | - wo_b=config.wo_b, | ||
| 126 | - compressor=_to_npu_compressor(compressor) if compressor is not None else None, | ||
| 127 | - indexer=_to_npu_indexer(config.indexer) if config.indexer is not None else None, | ||
| 128 | - lightning_indexer=( | ||
| 129 | - LightningIndexer.Config(index_topk=config.inner_attention.index_topk) | ||
| 130 | - if config.indexer is not None | ||
| 131 | - else None | ||
| 132 | - ), | ||
| 133 | - inner_attention=NPUCompressedSparseInnerAttention.Config( | ||
| 134 | - window_size=config.inner_attention.window_size, | ||
| 135 | - compress_ratio=compress_ratio, | ||
| 136 | - softmax_scale=config.inner_attention.softmax_scale, | ||
| 137 | - index_topk=config.inner_attention.index_topk, | ||
| 138 | - ), | ||
| 139 | - param_init=param_init or None, | ||
| 140 | - ) | ||
| 141 | - set_deepseek_v4_attention_sharding(result, enable_sp=enable_sp) | ||
| 142 | - return result | ||
| 143 | - | ||
| 144 | - | ||
| 145 | -def with_npu_attention_backend( | ||
| 146 | - config: DeepSeekV4Model.Config, | ||
| 147 | - *, | ||
| 148 | - enable_sp: bool = False, | ||
| 149 | -) -> NPUBackendDeepSeekV4Model.Config: | ||
| 150 | - """Select the NPU attention and state layout before applying child overrides.""" | ||
| 151 | - config = deepcopy(config) | ||
| 152 | - for layer in (*config.layers, *(config.mtp_layers or ())): | ||
| 153 | - attention = to_npu_attention_config(layer.attention, enable_sp=enable_sp) | ||
| 154 | - layer.attention = attention # pyrefly: ignore [bad-assignment] | ||
| 155 | - # The backend state adapter owns a concrete list of configured MTP stages. | ||
| 156 | - return derive(config, NPUBackendDeepSeekV4Model.Config, mtp_layers=config.mtp_layers or []) | ||