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"""Complete training-time KDA algorithm, independent of CP resource binding."""
16from __future__ import annotations
17
18from typing import Any
19
20import torch
21from torch import nn
22from torch.nn import functional as F
23
24from hyper_parallel.components.functional.kimi_delta_attention import (
25 chunk_kda,
26)
27from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import (
28 PackedSequenceInfo,
29)
30from hyper_parallel.components.functional.linear_attention_convolution import (
31 validate_causal_convolution,
32 run_causal_short_conv,
33)
34from hyper_parallel.components.functional.linear_attention_convolution import validate_conv_backend
35from hyper_parallel.components.modules.attention.linear_attention_utils.layer_adapter import (
36 adopt_source_parameters, copy_unbound_linear_attention, prepare_linear_attention_input,
37)
38
39class KimiRMSNormGated(nn.Module):
40 """Per-head RMSNorm followed by the sigmoid output gate used by KDA."""
41
42 def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
43 """Initialize the per-head normalization weight and epsilon."""
44 super().__init__()
45 self.weight = nn.Parameter(torch.ones(hidden_size))
46 self.variance_epsilon = eps
47
48 def forward(self, hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
49 """Normalize in FP32 and apply a sigmoid gate in the input dtype.
50
51 Args:
52 hidden_states: Attention output with per-head channels in the last dimension.
53 gate: Output-gate logits applied after RMS normalization.
54 """
55 input_dtype = hidden_states.dtype
56 normalized = hidden_states.float()
57 variance = normalized.square().mean(dim=-1, keepdim=True)
58 normalized = normalized * torch.rsqrt(variance + self.variance_epsilon)
59 normalized = normalized * self.weight.float()
60 return (normalized * gate.float().sigmoid()).to(input_dtype)
61
62
63def _make_short_convolution(channels: int, kernel_size: int) -> nn.Conv1d:
64 """Create the depthwise causal convolution used by the training layer."""
65 convolution = nn.Conv1d(
66 channels,
67 channels,
68 kernel_size=kernel_size,
69 groups=channels,
70 padding=kernel_size - 1,
71 bias=False,
72 )
73 convolution.activation = "silu"
74 return convolution
75
76
77class KimiDeltaAttentionModule(nn.Module):
78 """KDA projections, convolution, gated recurrence and output in one local algorithm."""
79
80 def __init__(self, *, config: Any = None, module: nn.Module | None = None,
81 backend: str = "eager", conv_backend: str | None = None,
82 chunk_size: int = 64, input_layout: str = "BSH") -> None:
83 """Construct local parameters or adopt source weights without renaming them."""
84 super().__init__()
85 if (config is None) == (module is None):
86 raise ValueError("KDA requires exactly one of config or module")
87 self.config = config if module is None else getattr(module, "config", None)
88 self.backend = backend
89 self.conv_backend = validate_conv_backend(backend if conv_backend is None else conv_backend)
90 self.chunk_size = chunk_size
91 self.input_layout = input_layout
92 self._config_initialization = module is None or getattr(module, "_config_initialization", False)
93 self._returns_tuple = False
94 if module is None:
95 self._initialize_parameters(config)
96 else:
97 self._adopt_source(module)
98 self._validate_local_contract()
99
100 def _validate_local_contract(self) -> None:
101 """Reject unsupported source semantics before running any local kernels."""
102 if self.use_short_conv:
103 for name in ("q_conv1d", "k_conv1d", "v_conv1d"):
104 validate_causal_convolution(getattr(self, name), require_activation=True)
105 if self.backend not in ("eager", "triton", "ascendc"):
106 raise ValueError("KDA backend must be eager, triton or ascendc")
107 if self.backend != "eager" and (self.head_k_dim != 128 or self.head_v_dim != 128 or self.chunk_size != 64):
108 raise ValueError("Fused KDA requires K=V=128 and chunk_size=64")
109 if getattr(self, "allow_neg_eigval", False):
110 raise NotImplementedError("KDA family does not support allow_neg_eigval=True")
111 if not self.safe_gate or self.lower_bound is None or self.lower_bound >= 0:
112 raise ValueError("KDA family requires its lower-bounded gate")
113
114 def __deepcopy__(self, memo: dict) -> nn.Module:
115 """Retain pre-binding model-copy behavior without copying process groups."""
116 return copy_unbound_linear_attention(self, memo)
117
118 def _initialize_parameters(self, config: Any) -> None:
119 """Keep the established standalone KDA parameter initialization."""
120 self.hidden_size = getattr(config, "hidden_size", None)
121 self.num_heads = getattr(config, "num_heads", 32)
122 self.num_k_heads = self.num_heads
123 self.num_v_heads = getattr(config, "num_v_heads", None)
124 self.head_k_dim = getattr(config, "head_k_dim", 128)
125 self.head_v_dim = getattr(config, "head_v_dim", 128)
126 self.conv_kernel_size = getattr(config, "conv_kernel_size", 4)
127 self.gate_lower_bound = getattr(config, "gate_lower_bound", -5.0)
128 self.use_full_rank_gate = getattr(config, "use_full_rank_gate", True)
129 self.layer_idx = getattr(config, "layer_idx", 0)
130 rms_norm_eps = getattr(config, "rms_norm_eps", 1e-6)
131 if self.hidden_size is None or self.hidden_size <= 0 or self.num_heads <= 0:
132 raise ValueError("hidden_size and num_heads must be positive.")
133 if self.num_v_heads is None:
134 self.num_v_heads = self.num_heads
135 if self.num_v_heads <= 0 or self.num_v_heads % self.num_heads:
136 raise ValueError("num_v_heads must be positive and divisible by num_heads.")
137 if self.head_k_dim <= 0 or self.head_v_dim <= 0:
138 raise ValueError("KDA head dimensions must be positive.")
139 if self.conv_kernel_size <= 0 or self.chunk_size <= 0:
140 raise ValueError("conv_kernel_size and chunk_size must be positive.")
141 if self.gate_lower_bound >= 0:
142 raise ValueError("gate_lower_bound must be negative.")
143
144 self.head_dim = self.head_v_dim
145 self.key_dim = self.num_heads * self.head_k_dim
146 self.value_dim = self.num_v_heads * self.head_v_dim
147 self.conv_size = self.conv_kernel_size
148 self.lower_bound = self.gate_lower_bound
149 self.safe_gate = True
150 self.allow_neg_eigval = False
151 self.use_short_conv = True
152
153 self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
154 self.k_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
155 self.v_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
156 self.q_conv1d = _make_short_convolution(self.key_dim, self.conv_kernel_size)
157 self.k_conv1d = _make_short_convolution(self.key_dim, self.conv_kernel_size)
158 self.v_conv1d = _make_short_convolution(self.value_dim, self.conv_kernel_size)
159
160 # A_log is the source model checkpoint key.
161 self.A_log = nn.Parameter(torch.empty(self.num_v_heads, dtype=torch.float32)) # pylint: disable=invalid-name
162 self.dt_bias = nn.Parameter(
163 torch.zeros(self.num_v_heads * self.head_k_dim, dtype=torch.float32)
164 )
165 with torch.no_grad():
166 self.A_log.copy_(torch.empty_like(self.A_log).uniform_(1, 16).log())
167
168 self.f_a_proj = nn.Linear(self.hidden_size, self.head_k_dim, bias=False)
169 self.f_b_proj = nn.Linear(self.head_k_dim, self.num_v_heads * self.head_k_dim, bias=False)
170 self.b_proj = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
171 if self.use_full_rank_gate:
172 self.g_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
173 else:
174 self.g_a_proj = nn.Linear(self.hidden_size, self.head_v_dim, bias=False)
175 self.g_b_proj = nn.Linear(self.head_v_dim, self.value_dim, bias=False)
176 self.o_norm = KimiRMSNormGated(self.head_v_dim, eps=rms_norm_eps)
177 self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
178
179
180 def _adopt_source(self, module: nn.Module) -> None:
181 """Adopt source parameters and dimensions without changing checkpoint keys."""
182 required = ("q_proj", "k_proj", "v_proj", "b_proj", "o_norm", "o_proj", "A_log", "dt_bias",
183 "num_heads", "head_k_dim")
184 missing = [name for name in required if not hasattr(module, name)]
185 if missing:
186 raise TypeError(f"KDA source is missing {missing}")
187 if not (hasattr(module, "f_proj") or all(hasattr(module, name) for name in ("f_a_proj", "f_b_proj"))):
188 raise TypeError("KDA source requires f_proj or f_a_proj/f_b_proj")
189 if not (hasattr(module, "g_proj") or all(hasattr(module, name) for name in ("g_a_proj", "g_b_proj"))):
190 raise TypeError("KDA source requires g_proj or g_a_proj/g_b_proj")
191 owners = ("q_proj", "k_proj", "v_proj", "q_conv1d", "k_conv1d", "v_conv1d", "A_log", "dt_bias",
192 "f_proj", "f_a_proj", "f_b_proj", "b_proj", "g_proj", "g_a_proj", "g_b_proj", "o_norm", "o_proj")
193 adopt_source_parameters(self, module, owners)
194 self.num_heads = self.num_k_heads = module.num_heads
195 self.num_v_heads = getattr(module, "num_v_heads", self.num_heads)
196 self.head_k_dim = module.head_k_dim
197 self.head_v_dim = getattr(module, "head_v_dim", getattr(module, "head_dim", None))
198 self.head_dim = self.head_v_dim
199 if self.num_v_heads % self.num_heads:
200 raise ValueError("KDA value heads must be divisible by query heads")
201 self.key_dim = self.num_heads * self.head_k_dim
202 self.value_dim = self.num_v_heads * self.head_v_dim
203 self.hidden_size = self.q_proj.in_features
204 self.layer_idx = getattr(module, "layer_idx", None)
205 self.lower_bound = getattr(module, "lower_bound", getattr(module, "gate_lower_bound", None))
206 self.gate_lower_bound = self.lower_bound
207 self.safe_gate = getattr(module, "safe_gate", self.lower_bound is not None)
208 self.allow_neg_eigval = getattr(module, "allow_neg_eigval", False)
209 self.use_short_conv = getattr(module, "use_short_conv", hasattr(module, "q_conv1d"))
210 self._returns_tuple = getattr(module, "_returns_tuple", not hasattr(module, "f_a_proj"))
211
212 @staticmethod
213 def make_transforms() -> list:
214 """Keep source checkpoint names and shapes unchanged during replacement.
215
216 Returns:
217 An empty conversion list; source Parameter objects are adopted directly.
218 """
219 return []
220
221 def reset_parameters(self) -> None:
222 """Reset native/meta construction, without resetting adopted source weights."""
223 if not self._config_initialization:
224 return
225 for child in self.children():
226 if isinstance(child, (nn.Linear, nn.Conv1d)):
227 child.reset_parameters()
228 nn.init.uniform_(self.A_log, 1, 16)
229 with torch.no_grad():
230 self.A_log.log_()
231 nn.init.zeros_(self.dt_bias)
232 nn.init.ones_(self.o_norm.weight)
233
234 def project_inputs(self, hidden_states: torch.Tensor) -> tuple:
235 """Project Q/K/V in the source order, before convolution or head exchange.
236
237 Args:
238 hidden_states: Local hidden activations in BSH or flat TH layout.
239 """
240 return self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
241
242 def project_state_gates(self, hidden_states: torch.Tensor) -> tuple:
243 """Produce raw decay and beta logits after the scheduled Q/K/V stage.
244
245 Args:
246 hidden_states: Local hidden activations in BSH or flat TH layout.
247 """
248 gate = self.f_proj(hidden_states) if hasattr(self, "f_proj") else self.f_b_proj(self.f_a_proj(hidden_states))
249 return gate, self.b_proj(hidden_states)
250
251 def project_output_gate(self, hidden_states: torch.Tensor) -> torch.Tensor:
252 """Keep source ordering of the output gate's shared-hidden gradient accumulation.
253
254 Args:
255 hidden_states: Local hidden activations in BSH or flat TH layout.
256 """
257 gate = self.g_proj(hidden_states) if hasattr(self, "g_proj") else self.g_b_proj(self.g_a_proj(hidden_states))
258 return gate.reshape(*hidden_states.shape[:2], self.num_v_heads, self.head_v_dim)
259
260 def convolve_inputs(self, operands: tuple, info: PackedSequenceInfo | None) -> tuple:
261 """Apply local convolutions before shaping heads.
262
263 Args:
264 operands: Projected inputs consumed by this attention stage.
265 info: Immutable packed-sequence metadata, or None for dense input.
266 """
267 query, key, value = operands
268 if self.use_short_conv:
269 query, key, value = (run_causal_short_conv(tensor, conv, sequence_info=info, backend=self.conv_backend)
270 for tensor, conv in zip((query, key, value),
271 (self.q_conv1d, self.k_conv1d, self.v_conv1d)))
272 else:
273 query, key, value = (F.silu(tensor) for tensor in (query, key, value))
274 return query, key, value
275
276 def shape_inputs(self, operands: tuple, degree: int = 1) -> tuple:
277 """Expose head axes without changing raw gate or beta semantics.
278
279 Args:
280 operands: Projected inputs consumed by this attention stage.
281 degree: Number of ranks participating in the head/sequence exchange.
282 """
283 query, key, value, gate, beta = operands
284 batch, tokens = query.shape[:2]
285 kh, vh = self.num_heads // degree, self.num_v_heads // degree
286 return (query.reshape(batch, tokens, kh, self.head_k_dim),
287 key.reshape(batch, tokens, kh, self.head_k_dim),
288 value.reshape(batch, tokens, vh, self.head_v_dim),
289 gate.reshape(batch, tokens, vh, self.head_k_dim), beta.reshape(batch, tokens, vh))
290
291 def run_local_core(self, operands: tuple, info: PackedSequenceInfo | None,
292 a_log: torch.Tensor | None = None, dt_bias: torch.Tensor | None = None) -> torch.Tensor:
293 """Invoke the selected complete local autograd without CP transport.
294
295 Args:
296 operands: Projected inputs consumed by this attention stage.
297 info: Immutable packed-sequence metadata, or None for dense input.
298 a_log: Log decay-rate parameter.
299 dt_bias: Per-key time-step bias.
300 """
301 offsets = None
302 if info is not None:
303 offsets = (info.local_offsets if self.backend in ("eager", "ascendc") else
304 info.materialize(operands[0].device, self.chunk_size).cu_seqlens)
305 return chunk_kda(*operands, a_log=self.A_log if a_log is None else a_log,
306 dt_bias=self.dt_bias if dt_bias is None else dt_bias,
307 initial_state=None, output_final_state=False, chunk_size=self.chunk_size,
308 use_qk_l2norm_in_kernel=True, use_gate_in_kernel=True,
309 use_beta_sigmoid_in_kernel=True, lower_bound=self.lower_bound,
310 backend=self.backend, cu_seqlens=offsets)[0]
311
312 def execute_attention_pipeline(self, hidden_states: torch.Tensor,
313 info: PackedSequenceInfo | None) -> tuple:
314 """Keep local convolution, state gates and output-gate ordering unchanged.
315
316 Args:
317 hidden_states: Local hidden activations in BSH or flat TH layout.
318 info: Immutable packed-sequence metadata, or None for dense input.
319 """
320 projected = self.convolve_inputs(self.project_inputs(hidden_states), info)
321 gate, beta = self.project_state_gates(hidden_states)
322 output = self.run_local_core(self.shape_inputs((*projected, gate, beta)), info)
323 return output, self.project_output_gate(hidden_states)
324
325 def project_output(self, output: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
326 """Apply the source normalization/gate and output projection in token layout.
327
328 Args:
329 output: Local attention output before its final projection.
330 gate: Output-gate logits applied after normalization.
331 """
332 output = self.o_norm(output, gate)
333 return self.o_proj(output.reshape(*output.shape[:2], self.value_dim))
334
335 def prepare_input(self, hidden_states: torch.Tensor, options: dict) -> tuple:
336 """Adapt local dense/flat input; CP members resolve their own token interval.
337
338 Args:
339 hidden_states: Local dense or flat hidden activations.
340 options: Explicit backend options or invocation document metadata.
341 """
342 return prepare_linear_attention_input(hidden_states, options)
343
344 def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None,
345 past_key_values: Any = None, use_cache: bool = False, output_attentions: bool = False,
346 **kwargs: Any) -> Any:
347 """Run dense or packed training KDA, retaining the source output structure.
348
349 Args:
350 hidden_states: Local hidden activations in BSH or flat TH layout.
351 attention_mask: Optional source-model mask; packed boundaries carry document resets.
352 past_key_values: Source-model inference cache; training-family execution requires None.
353 use_cache: Inference-cache request; unsupported by this training entry.
354 output_attentions: Source-model attention-weight request; KDA returns no attention matrix.
355 """
356 if use_cache or past_key_values is not None or kwargs.get("cache_params") is not None:
357 raise NotImplementedError("KDA family supports training without recurrent cache")
358 if output_attentions:
359 raise NotImplementedError("KDA does not materialize attention weights")
360 if attention_mask is not None and not bool(attention_mask.bool().all().item()):
361 raise NotImplementedError("Padded KDA batches are not implemented")
362 hidden_states, info, is_flat_input = self.prepare_input(hidden_states, kwargs)
363 output, gate = self.execute_attention_pipeline(hidden_states, info)
364 del hidden_states
365 output = self.project_output(output, gate)
366 if is_flat_input:
367 output = output.squeeze(0)
368 return (output, None, None) if self._returns_tuple else output