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"""KimiDeltaAttention family selection; backend and communication are independent options."""
16from __future__ import annotations
17
18from types import SimpleNamespace
19from typing import Any
20from torch import nn
21
22from hyper_parallel.core.dtensor.placement_types import Replicate, Shard
23from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec
24
25from hyper_parallel.components.modules.module_family import (
26 ModuleFamily, VariantRule, build_family, register_module_family,
27)
28from hyper_parallel.components.modules.attention.linear_attention_utils.parallel_layout import (
29 linear_attention_local_spec, linear_attention_sharding, validate_state_packets,
30)
31from hyper_parallel.components.modules.attention.linear_attention_utils.layer_adapter import validate_backend_options
32from hyper_parallel.models.replacement import module_replacement
33from .kimi_delta_attention import KimiDeltaAttentionModule
34
35
36def _validate_kda_state_protocol(options: Any, cp: int, degree: int, backend: str) -> None:
37 """Keep state protocol qualifications separate from layout validation."""
38 protocol = options.get("state_cp_method", "p2p")
39 if protocol not in ("p2p", "allgather", "alltoallv", "grouped_allgather_p2p", "recursive_doubling"):
40 raise ValueError("Unknown KDA state_cp_method")
41 group = options.get("allgather_group_size", 1)
42 if (not isinstance(group, int) or isinstance(group, bool)) or group < 1 or (cp > 1 and (cp // degree) % group):
43 raise ValueError("allgather_group_size must divide state CP size")
44 if group != 1 and protocol != "grouped_allgather_p2p":
45 raise ValueError("allgather_group_size is only valid for grouped_allgather_p2p")
46 if cp > degree and backend == "eager":
47 raise NotImplementedError("Eager KDA supports local/pure Ulysses only; state CP requires Triton or Ascend C")
48
49
50def validate_kda_family(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
51 """Check this family's supported algorithms before constructing parameters or groups."""
52 del context
53 backend = validate_backend_options(member.arguments)
54 cp = member.axis_sizes["cp"]
55 degree = member.arguments.get("ulysses_degree", 1)
56 degree = cp if degree is None else degree
57 if (not isinstance(degree, int) or isinstance(degree, bool)) or degree < 1 or (cp > 1 and cp % degree):
58 raise ValueError("ulysses_degree must be a positive divisor of CP size")
59 source = config if module is None else module
60 kh = getattr(source, "num_heads", None)
61 vh = getattr(source, "num_v_heads", None) or kh
62 head_degree = member.axis_sizes["tp"] * (degree if cp > 1 else 1)
63 if kh is not None and (kh % head_degree or vh % head_degree):
64 raise ValueError("TP times Ulysses degree must divide both query and value heads")
65 _validate_kda_state_protocol(member.arguments, cp, degree, backend)
66 validate_state_packets(member.arguments, cp, degree, backend, None if vh is None else vh // head_degree)
67
68
69def kda_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
70 """Declare head ownership without splitting the shared low-rank gate inputs.
71
72 Args:
73 module: KDA family member with source-owned projection parameters.
74 module_fqn: Source path supplied by the common layout planner.
75 member: Resolved family selection.
76 context: Logical TP/CP sizes and SP mode.
77 """
78 del module_fqn, member
79 columns = ("q_proj", "k_proj", "v_proj", "b_proj", "f_b_proj", "g_b_proj",
80 "q_conv1d", "k_conv1d", "v_conv1d")
81 roles = {f"{name}.{suffix}": Shard(0) for name in columns for suffix in ("weight", "bias")}
82 roles.update({f"{name}.{suffix}": Replicate() for name in ("f_a_proj", "g_a_proj", "o_norm")
83 for suffix in ("weight", "bias")})
84 roles.update({"A_log": Shard(0), "dt_bias": Shard(0),
85 "o_proj.weight": Shard(1), "o_proj.bias": Replicate()})
86 for name in ("f_proj", "g_proj"):
87 projection = getattr(module, name, None)
88 if projection is None:
89 continue
90 linears = [(path, child) for path, child in projection.named_modules() if isinstance(child, nn.Linear)]
91 for index, (path, _) in enumerate(linears):
92 owner = f"{name}.{path}" if path else name
93 placement = Shard(0) if index == len(linears) - 1 else Replicate()
94 roles.update({f"{owner}.{suffix}": placement for suffix in ("weight", "bias")})
95 return linear_attention_sharding(module=module, context=context, roles=roles,
96 tp_divide_attrs=("num_k_heads", "num_v_heads", "key_dim", "value_dim"))
97
98
99def _build_local(
100 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "", context: Any = None,
101 backend: str = "eager", conv_backend: str | None = None, chunk_size: int = 64,
102 input_layout: str = "BSH", ulysses_degree: int | None = 1,
103 state_cp_method: str = "p2p", allgather_group_size: int = 1,
104 p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False,
105) -> nn.Module:
106 """Keep CP selection in the family request, outside the standalone algorithm."""
107 del module_fqn, context, ulysses_degree, state_cp_method, allgather_group_size
108 del p2p_head_chunks, reuse_cp_state_on_recompute
109 return KimiDeltaAttentionModule(config=config, module=module, backend=backend, conv_backend=conv_backend,
110 chunk_size=chunk_size, input_layout=input_layout)
111
112
113# Public factories follow the ModuleFamily class-style naming convention.
114@module_replacement
115def KimiDeltaAttention( # pylint: disable=invalid-name
116 *, config: Any = None, module: nn.Module | None = None, module_fqn: str = "",
117 context: Any = None, mesh: Any = None, backend: str = "eager", conv_backend: str | None = None,
118 chunk_size: int = 64, input_layout: str = "BSH", ulysses_degree: int | None = 1,
119 state_cp_method: str = "p2p", allgather_group_size: int = 1,
120 p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False,
121 hidden_size: int | None = None, num_heads: int = 32, num_v_heads: int | None = None,
122 head_k_dim: int = 128, head_v_dim: int = 128, conv_kernel_size: int = 4,
123 gate_lower_bound: float = -5.0, use_full_rank_gate: bool = True, rms_norm_eps: float = 1e-6,
124 layer_idx: int = 0,
125) -> nn.Module:
126 """Build the complete local or CP training member with source checkpoint names.
127
128 Args:
129 config: Direct model dimensions; mutually exclusive with module.
130 module: Existing supported source whose parameters are retained.
131 module_fqn: Path supplied by model replacement.
132 context: Logical parallel degrees for selection without process groups.
133 mesh: Existing runtime mesh for layout and resource binding.
134 backend: Explicit eager, triton or ascendc attention implementation.
135 conv_backend: Independent convolution implementation; omission preserves scheduling defaults.
136 chunk_size: Local chunk length; fused implementations require 64.
137 input_layout: BSH or TH, determining the external token shard axis.
138 ulysses_degree: Head-exchange degree; None selects pure Ulysses scheduling.
139 state_cp_method: Ordered state exchange: p2p, allgather, alltoallv, grouped_allgather_p2p or recursive_doubling.
140 allgather_group_size: Contiguous state-group width for grouped_allgather_p2p.
141 p2p_head_chunks: Head packets for Ascend C state P2P; does not split local kernel production.
142 reuse_cp_state_on_recompute: Retain the native CP entry across outer checkpoint replay; default False.
143 hidden_size: Legacy direct-construction model width; exclusive with config and module.
144 num_heads: Query/key head count for direct construction.
145 num_v_heads: Value head count; defaults to num_heads.
146 head_k_dim: Channels per query/key head.
147 head_v_dim: Channels per value head.
148 conv_kernel_size: Causal depthwise convolution width.
149 gate_lower_bound: Negative lower bound used by the safe decay gate.
150 use_full_rank_gate: Whether direct construction uses a full-width output gate.
151 rms_norm_eps: Output normalization epsilon.
152 layer_idx: Source layer index retained in direct construction.
153 """
154 if hidden_size is not None:
155 if config is not None or module is not None:
156 raise ValueError("hidden_size construction cannot be combined with config or module")
157 config = SimpleNamespace(hidden_size=hidden_size, num_heads=num_heads, num_v_heads=num_v_heads,
158 head_k_dim=head_k_dim, head_v_dim=head_v_dim, conv_kernel_size=conv_kernel_size,
159 gate_lower_bound=gate_lower_bound, use_full_rank_gate=use_full_rank_gate,
160 rms_norm_eps=rms_norm_eps, layer_idx=layer_idx)
161 return build_family(KimiDeltaAttention, config=config, module=module, module_fqn=module_fqn,
162 context=context, mesh=mesh, backend=backend, conv_backend=conv_backend,
163 chunk_size=chunk_size, input_layout=input_layout, ulysses_degree=ulysses_degree,
164 state_cp_method=state_cp_method, allgather_group_size=allgather_group_size,
165 p2p_head_chunks=p2p_head_chunks, reuse_cp_state_on_recompute=reuse_cp_state_on_recompute)
166
167
168register_module_family(ModuleFamily(
169 name="kimi_delta_attention", baseline=KimiDeltaAttention,
170 variants={
171 "local": ("hyper_parallel.components.modules.attention.kimi_delta_attention."
172 "kimi_delta_attention_family._build_local"),
173 "cp": ("hyper_parallel.components.modules.attention.kimi_delta_attention."
174 "cp_kimi_delta_attention.CPKimiDeltaAttentionModule"),
175 },
176 default_variant="local", parallel_axis="cp", variant_rules=(VariantRule({"parallel": True}, "cp"),),
177 sharding=kda_sharding, validate=validate_kda_family,
178 parallel_spec=linear_attention_local_spec,
179))