1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""DeepSeek sparse-attention families, parameter layouts and parallel initialization."""
16
17from __future__ import annotations
18
19from typing import Any
20
21from torch import nn
22
23from hyper_parallel.components.modules.module_family import (
24 ModuleFamily, VariantRule, build_family, register_module_family,
25)
26from hyper_parallel.core.dtensor.placement_types import Partial, Replicate, Shard
27from hyper_parallel.distributed._builder.family_layout import validate_tp_boundary
28from hyper_parallel.distributed.module_binding import ParallelModuleSpec
29from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
30from hyper_parallel.models.replacement import module_replacement
31
32
33def validate_sparse_attention_family(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
34 """Check logical topology before allocating native or replacement parameters."""
35 # Local/meta construction can retain a CP request before the job topology exists.
36 cp_size = context.get("cp_size")
37 if cp_size is not None and member.arguments.get("kv_cp_size", 1) != cp_size:
38 raise ValueError("kv_cp_size must equal the job cp_size")
39 config = config if module is None else module.config
40 if member.axis_sizes["pp"] > 1:
41 raise ValueError("DeepSeek sparse attention does not support pipeline parallelism")
42 heads = getattr(module, "num_heads", getattr(config, "num_attention_heads", None))
43 if heads % member.axis_sizes["tp"]:
44 raise ValueError("Sparse-attention heads must be divisible by TP degree")
45
46
47def sparse_attention_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
48 """Declare every owned parameter and external token port without name fallbacks."""
49 del module_fqn, member
50 placements = {axis: Replicate() for axis in context.mesh_dim_names if axis in context.axis_sizes}
51 column_names = ("q_b_proj", "kv_b_proj")
52 replica_names = (
53 "linear_qkv", "q_a_layernorm", "kv_a_layernorm",
54 "indexer.wq_b", "indexer.wk", "indexer.k_norm", "indexer.weights_proj",
55 )
56 columns = {f"{name}.{suffix}" for name in column_names for suffix in ("weight", "bias")}
57 replicas = {
58 f"{name}.{suffix}"
59 for name in replica_names
60 for suffix in ("weight", "bias")
61 }
62 roles = {
63 **dict.fromkeys(columns, Shard(0)), **dict.fromkeys(replicas, Replicate()),
64 "o_proj.weight": Shard(1), "o_proj.bias": Replicate(),
65 }
66 params = {}
67 for name, _ in module.named_parameters(remove_duplicate=False):
68 if name not in roles:
69 raise ValueError(f"Sparse-attention parameter {name!r} has no declared sharding role")
70 params[name] = dict(placements)
71 if context.axis_sizes["tp"] > 1:
72 params[name]["tp"] = roles[name]
73 tokens = dict(placements)
74 if context.axis_sizes["cp"] > 1:
75 tokens["cp"] = Shard(1)
76 if context.axis_sizes["tp"] > 1 and context.sequence_parallel:
77 tokens["tp"] = Shard(1)
78 compute_input, output = dict(tokens), dict(tokens)
79 if context.axis_sizes["tp"] > 1:
80 compute_input["tp"] = Replicate()
81 output["tp"] = Partial()
82 return ModuleShardingSpec(
83 params=params, in_src={"hidden_states": dict(tokens)}, in_dst={"hidden_states": compute_input},
84 out_src={"output": output}, out_dst={"output": dict(tokens)},
85 out_names=("output", "attention_weights"), is_boundary=True,
86 )
87
88
89def validate_sparse_attention_layout(*, module: nn.Module, sharding: Any, context: Any) -> None:
90 """Validate the declared token and projection layouts after recipe overrides."""
91 expected = sparse_attention_sharding(module=module, module_fqn="", member=None, context=context)
92 validate_tp_boundary(sharding, expected, name="DeepSeek sparse attention")
93 if tuple(sharding.out_names or ()) != tuple(expected.out_names):
94 raise ValueError("Sparse-attention output names must preserve the declared return contract")
95
96
97def sparse_attention_parallel_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
98 """Declare shared algorithm stages and validate layouts outside local computation."""
99 del module, member
100 return ParallelModuleSpec(
101 "attention.deepseek_sparse_attention.local", binding_kind="mesh",
102 stages={
103 "preflight_attention": (
104 "hidden_states", "attention_mask", "past_key_values", "position_ids",
105 "actual_seq_len", "kwargs", "use_dense",
106 ),
107 "prepare_attention_inputs": ("hidden_states", "position_embeddings", "metadata", "use_dense"),
108 "exchange_attention": ("inputs",),
109 "run_attention": ("index_states", "attention_states", "sequence_lengths", "use_dense"),
110 "project_output": ("output",),
111 },
112 validate=validate_sparse_attention_layout,
113 )
114
115
116@module_replacement
117def DeepseekSparseAttention( # pylint: disable=invalid-name
118 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "",
119 context: Any = None, mesh: Any = None,
120 kv_cp_size: int = 1, kv_cp_strategy: str = "allgather",
121 cp_comm_overlap: bool = False, dense_warmup: bool | None = None,
122) -> nn.Module:
123 """Build a local or CP member while retaining V3.2 source and checkpoint contracts.
124
125 Args:
126 config: Native attention dimensions and options; mutually exclusive with module.
127 module: HF attention source or an already loaded unbound local member.
128 module_fqn: Source path supplied by the replacement executor.
129 context: Logical job topology used for family selection.
130 mesh: Optional existing MeshContext for shared layout planning and binding.
131 kv_cp_size: KV domain size; must equal the job CP size for this implementation.
132 kv_cp_strategy: KV transport; currently only allgather is supported.
133 cp_comm_overlap: Submit all key-bank gathers before waiting when true; defaults to False.
134 dense_warmup: None follows the mutable model stage; bool pins the stage.
135
136 Returns:
137 Concrete member retaining the requested family and parameter layout.
138 """
139 return build_family(
140 DeepseekSparseAttention, config=config, module=module, module_fqn=module_fqn, context=context,
141 mesh=mesh, kv_cp_size=kv_cp_size, kv_cp_strategy=kv_cp_strategy,
142 cp_comm_overlap=cp_comm_overlap, dense_warmup=dense_warmup,
143 )
144
145
146register_module_family(ModuleFamily(
147 name="deepseek_sparse_attention", baseline=DeepseekSparseAttention,
148 variants={
149 "local": (
150 "hyper_parallel.components.modules.attention.deepseek_sparse_attention."
151 "deepseek_sparse_attention.DeepseekSparseAttentionModule"
152 ),
153 "cp": (
154 "hyper_parallel.components.modules.attention.deepseek_sparse_attention."
155 "cp_deepseek_sparse_attention.CPDeepseekSparseAttentionModule"
156 ),
157 },
158 default_variant="local", parallel_axis="cp",
159 variant_rules=(VariantRule({"parallel": True}, "cp"),),
160 sharding=sparse_attention_sharding, validate=validate_sparse_attention_family,
161 parallel_spec=sparse_attention_parallel_spec,
162))