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"""FLA Triton-Ascend KDA stages, state summaries and ordered affine scans."""
16from __future__ import annotations
17import importlib
18import importlib.util
19import re
20from dataclasses import dataclass
21from functools import lru_cache
22from typing import Any, Callable, Optional
23
24import torch
25
26
27_MIN_FLA_VERSION = (0, 6, 0)
28
29
30@dataclass(frozen=True)
31class FLAKDAStagedOps:
32 """FLA operators required around Hyper's affine state summary."""
33
34 l2norm_fwd: Callable[..., Any]
35 l2norm_bwd: Callable[..., Any]
36 fused_beta_sigmoid: Callable[..., Any]
37 fused_beta_sigmoid_bwd: Callable[..., Any]
38 kda_gate_chunk_cumsum: Callable[..., Any]
39 kda_gate_bwd: Callable[..., Any]
40 chunk_kda_fwd_intra: Callable[..., Any]
41 recompute_w_u_fwd: Callable[..., Any]
42 chunk_gated_delta_rule_fwd_h: Callable[..., Any]
43 chunk_gla_fwd_o_gk: Callable[..., Any]
44 chunk_kda_bwd_dav: Callable[..., Any]
45 chunk_gated_delta_rule_bwd_dhu: Callable[..., Any]
46 chunk_kda_bwd_wy_dqkg_fused: Callable[..., Any]
47 chunk_kda_bwd_intra: Callable[..., Any]
48 chunk_local_cumsum: Callable[..., Any]
49
50
51@dataclass(frozen=True)
52class _FLAKDARuntime:
53 """Resolved external FLA runtime and its required KDA entry points."""
54
55 version: str
56 chunk_kda: Callable[..., Any]
57
58
59def _get_attribute(module_name: str, attribute: str) -> Any:
60 """Import one required FLA symbol with a useful compatibility error."""
61 # OpSelect imports this adapter during registration; defer its dependency loader.
62 from hyper_parallel.components.ops._dependency import import_fla_module # pylint: disable=import-outside-toplevel
63 try:
64 module = import_fla_module(module_name)
65 except ModuleNotFoundError as exc:
66 missing_name = getattr(exc, "name", None)
67 is_fla_module = (
68 missing_name is not None and str(missing_name).startswith("fla.")
69 )
70 if missing_name == module_name or is_fla_module:
71 raise RuntimeError(
72 "The installed FLA package is incompatible with Hyper KDA: "
73 f"missing module {module_name}."
74 ) from exc
75 raise RuntimeError(
76 f"FLA module {module_name} could not load runtime dependency "
77 f"{missing_name!r}."
78 ) from exc
79 except ImportError as exc:
80 raise RuntimeError(
81 f"FLA module {module_name} failed to import; inspect the chained "
82 "exception for the incompatible runtime library."
83 ) from exc
84 try:
85 return getattr(module, attribute)
86 except AttributeError as exc:
87 raise RuntimeError(
88 "The installed FLA package is incompatible with Hyper KDA: "
89 f"missing {module_name}.{attribute}. Install an FLA revision with "
90 "the Triton-Ascend KDA backend."
91 ) from exc
92
93
94def _parse_version(version: str) -> tuple[int, int, int]:
95 """Parse the numeric prefix of an FLA semantic version."""
96 match = re.match(r"^(\d+)\.(\d+)\.(\d+)", version)
97 if match is None:
98 raise RuntimeError(f"Unable to parse the installed FLA version {version!r}.")
99 return tuple(int(part) for part in match.groups())
100
101
102def _require_triton_ascend() -> None:
103 """Require the external FLA runtime to have a Triton Ascend backend."""
104 try:
105 importlib.import_module("triton")
106 ascend_backend = importlib.util.find_spec("triton.backends.ascend")
107 except (ImportError, ModuleNotFoundError) as exc:
108 raise RuntimeError(
109 "KDA backend='triton' requires Triton-Ascend in the runtime environment."
110 ) from exc
111 if ascend_backend is None:
112 raise RuntimeError(
113 "KDA backend='triton' found Triton, but its Ascend backend is missing."
114 )
115
116
117def _require_npu_backends() -> None:
118 """Verify that FLA registered every backend used by the staged P2P path."""
119 backend_specs = (
120 (
121 "fla.ops.kda.backends.triton_ascend",
122 "TritonAscendKDABackend",
123 ),
124 (
125 "fla.ops.common.backends.triton_ascend",
126 "TritonAscendCommonBackend",
127 ),
128 (
129 "fla.ops.gla.backends.triton_ascend",
130 "TritonAscendGLABackend",
131 ),
132 )
133 for module_name, class_name in backend_specs:
134 backend = _get_attribute(module_name, class_name)
135 if not backend.is_available():
136 raise RuntimeError(
137 "KDA backend='triton' requires FLA's Triton-Ascend backend "
138 f"{class_name}, but it is unavailable in this process."
139 )
140
141
142@lru_cache(maxsize=1)
143def _require_fla_kda_runtime() -> _FLAKDARuntime:
144 """Resolve and validate the optional external FLA dependency once."""
145 # OpSelect imports this adapter during registration; defer its dependency loader.
146 from hyper_parallel.components.ops._dependency import import_fla_module # pylint: disable=import-outside-toplevel
147 try:
148 fla = import_fla_module("fla")
149 except ModuleNotFoundError as exc:
150 missing_name = getattr(exc, "name", None)
151 if missing_name != "fla":
152 raise RuntimeError(
153 "The external FLA package is present but cannot load runtime "
154 f"dependency {missing_name!r}."
155 ) from exc
156 raise RuntimeError(
157 "KDA backend='triton' requires the optional flash-linear-attention "
158 "package with its Triton-Ascend KDA backend."
159 ) from exc
160 except ImportError as exc:
161 raise RuntimeError(
162 "The external FLA package is present but failed to import; inspect "
163 "the chained exception for the incompatible runtime library."
164 ) from exc
165
166 version = getattr(fla, "__version__", None)
167 if not isinstance(version, str):
168 raise RuntimeError("The installed FLA package does not expose __version__.")
169 if _parse_version(version) < _MIN_FLA_VERSION:
170 minimum = ".".join(str(part) for part in _MIN_FLA_VERSION)
171 raise RuntimeError(
172 f"KDA backend='triton' requires FLA >= {minimum}, got {version}."
173 )
174
175 _require_triton_ascend()
176 backend = _get_attribute("fla.ops.kda.backends.triton_ascend", "TritonAscendKDABackend")
177 if not backend.is_available():
178 raise RuntimeError("FLA Triton-Ascend KDA backend is unavailable in this process.")
179 return _FLAKDARuntime(version=version, chunk_kda=_get_attribute("fla.ops.kda", "chunk_kda"))
180
181
182def is_fla_triton_kda_available() -> bool:
183 """Return whether the optional external FLA KDA backend is usable."""
184 try:
185 _require_fla_kda_runtime()
186 except RuntimeError:
187 return False
188 return True
189
190
191@lru_cache(maxsize=1)
192def get_fla_kda_staged_ops() -> FLAKDAStagedOps:
193 """Return FLA staged operators for Hyper's state-P2P autograd function."""
194 _require_fla_kda_runtime()
195 _require_npu_backends()
196 return FLAKDAStagedOps(
197 l2norm_fwd=_get_attribute("fla.modules.l2norm", "l2norm_fwd"),
198 l2norm_bwd=_get_attribute("fla.modules.l2norm", "l2norm_bwd"),
199 fused_beta_sigmoid=_get_attribute(
200 "fla.ops.common.gate", "fused_beta_sigmoid"
201 ),
202 fused_beta_sigmoid_bwd=_get_attribute(
203 "fla.ops.common.gate", "fused_beta_sigmoid_bwd"
204 ),
205 kda_gate_chunk_cumsum=_get_attribute(
206 "fla.ops.kda.gate", "kda_gate_chunk_cumsum"
207 ),
208 kda_gate_bwd=_get_attribute("fla.ops.kda.gate", "kda_gate_bwd"),
209 chunk_kda_fwd_intra=_get_attribute(
210 "fla.ops.kda.chunk_intra", "chunk_kda_fwd_intra"
211 ),
212 recompute_w_u_fwd=_get_attribute(
213 "fla.ops.kda.wy_fast", "recompute_w_u_fwd"
214 ),
215 chunk_gated_delta_rule_fwd_h=_get_attribute(
216 "fla.ops.common.chunk_delta_h", "chunk_gated_delta_rule_fwd_h"
217 ),
218 chunk_gla_fwd_o_gk=_get_attribute(
219 "fla.ops.gla.chunk", "chunk_gla_fwd_o_gk"
220 ),
221 chunk_kda_bwd_dav=_get_attribute(
222 "fla.ops.kda.chunk_bwd", "chunk_kda_bwd_dAv"
223 ),
224 chunk_gated_delta_rule_bwd_dhu=_get_attribute(
225 "fla.ops.common.chunk_delta_h", "chunk_gated_delta_rule_bwd_dhu"
226 ),
227 chunk_kda_bwd_wy_dqkg_fused=_get_attribute(
228 "fla.ops.kda.chunk_bwd", "chunk_kda_bwd_wy_dqkg_fused"
229 ),
230 chunk_kda_bwd_intra=_get_attribute(
231 "fla.ops.kda.chunk_intra", "chunk_kda_bwd_intra"
232 ),
233 chunk_local_cumsum=_get_attribute(
234 "fla.ops.utils.cumsum", "chunk_local_cumsum"
235 ),
236 )
237
238
239def run_fla_chunk_kda(
240 query: torch.Tensor,
241 key: torch.Tensor,
242 value: torch.Tensor,
243 gate: torch.Tensor,
244 beta: torch.Tensor,
245 *,
246 a_log: torch.Tensor,
247 dt_bias: torch.Tensor,
248 scale: Optional[float] = None,
249 initial_state: Optional[torch.Tensor] = None,
250 output_final_state: bool = False,
251 lower_bound: float = -5.0,
252 chunk_size: int = 64,
253 safe_gate: bool = True,
254 cu_seqlens: Optional[torch.Tensor] = None,
255) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
256 """Run FLA's public KDA API with the validated Kimi K3 fused contract.
257
258 Args:
259 query: Raw query tensor before fused normalization.
260 key: Raw key tensor before fused normalization.
261 value: Value tensor in the input token layout.
262 gate: Raw gate projection before the fused decay transform.
263 beta: Raw beta projection before the fused sigmoid.
264 a_log: Learned log-scale of the gate transform.
265 dt_bias: Learned gate bias.
266 scale: Optional attention scale; FLA supplies the default when omitted.
267 initial_state: Optional incoming recurrent state.
268 output_final_state: Whether to return the outgoing recurrent state.
269 lower_bound: Lower bound of the safe gate transform.
270 chunk_size: Token chunk size accepted by the selected fused implementation.
271 safe_gate: Whether to use the bounded gate transform.
272 cu_seqlens: Optional cumulative document boundaries for packed input.
273
274 Returns:
275 Attention output and the optional outgoing state.
276 """
277 runtime = _require_fla_kda_runtime()
278 return runtime.chunk_kda(
279 q=query,
280 k=key,
281 v=value,
282 g=gate,
283 beta=beta,
284 A_log=a_log,
285 dt_bias=dt_bias,
286 scale=scale,
287 initial_state=initial_state,
288 output_final_state=output_final_state,
289 use_qk_l2norm_in_kernel=True,
290 use_gate_in_kernel=True,
291 use_beta_sigmoid_in_kernel=True,
292 safe_gate=safe_gate,
293 lower_bound=lower_bound,
294 chunk_size=chunk_size,
295 cu_seqlens=cu_seqlens,
296 )
297
298
299def _validate_local_shapes(
300 query: torch.Tensor,
301 key: torch.Tensor,
302 value: torch.Tensor,
303 gate: torch.Tensor,
304 beta: torch.Tensor,
305) -> tuple[int, int, int, int]:
306 """Validate local KDA tensor shapes and return dimensions used by later checks."""
307 if (query.ndim, key.ndim, value.ndim, gate.ndim) != (4, 4, 4, 4):
308 raise ValueError("Fused KDA expects rank-4 query/key/value/gate tensors.")
309 if beta.ndim != 3:
310 raise ValueError("Fused KDA expects a rank-3 beta tensor.")
311 if query.shape != key.shape:
312 raise ValueError("Fused KDA query and key must have identical shapes.")
313 batch, sequence_length, num_query_heads, key_dim = query.shape
314 num_value_heads, value_dim = value.shape[2:]
315 if value.shape[:2] != (batch, sequence_length):
316 raise ValueError("Fused KDA value must match query batch and sequence dimensions.")
317 if gate.shape != (batch, sequence_length, num_value_heads, key_dim):
318 raise ValueError("Fused KDA gate has an incompatible shape.")
319 if beta.shape != (batch, sequence_length, num_value_heads):
320 raise ValueError("Fused KDA beta has an incompatible shape.")
321 if num_value_heads % num_query_heads:
322 raise ValueError("Fused KDA value heads must be divisible by query heads.")
323 return sequence_length, key_dim, value_dim, num_value_heads
324
325
326def validate_triton_kda_inputs(
327 query: torch.Tensor,
328 key: torch.Tensor,
329 value: torch.Tensor,
330 gate: torch.Tensor,
331 beta: torch.Tensor,
332 a_log: torch.Tensor,
333 dt_bias: torch.Tensor,
334 *,
335 chunk_size: int,
336 lower_bound: float,
337) -> None:
338 """Validate paired Triton KDA inputs before local kernels or state communication.
339
340 Args:
341 query: BF16 queries [B,T,H,K].
342 key: BF16 keys matching query.
343 value: BF16 values with compatible token and head axes.
344 gate: Raw BF16 channel gate logits.
345 beta: Raw BF16 per-head update logits.
346 a_log: FP32 per-head decay parameter.
347 dt_bias: FP32 per-channel gate bias.
348 chunk_size: Kernel chunk size, currently 64.
349 lower_bound: Safe gate lower bound in [-5,0).
350 """
351 _, key_dim, value_dim, num_value_heads = _validate_local_shapes(
352 query, key, value, gate, beta
353 )
354 if not (
355 query.dtype == key.dtype == value.dtype == gate.dtype == beta.dtype
356 == torch.bfloat16
357 ):
358 raise TypeError("Fused KDA requires q/k/v/gate/beta tensors in bfloat16.")
359 if a_log.dtype != torch.float32 or dt_bias.dtype != torch.float32:
360 raise TypeError("Fused KDA requires a_log and dt_bias tensors in float32.")
361 if key_dim != 128 or value_dim != 128 or chunk_size != 64:
362 raise NotImplementedError(
363 "Fused KDA currently requires key_dim=value_dim=128 and chunk_size=64."
364 )
365 if a_log.numel() != num_value_heads:
366 raise ValueError("Fused KDA a_log must contain one value per value head.")
367 if dt_bias.numel() != num_value_heads * key_dim:
368 raise ValueError("Fused KDA dt_bias must contain one value per gate channel.")
369 if not -5.0 <= lower_bound < 0:
370 raise ValueError("Fused KDA lower_bound must lie in [-5, 0).")
371 if not query.is_npu:
372 raise RuntimeError("The fused KDA backend requires Ascend NPU tensors.")
373 if any(
374 tensor.device != query.device
375 for tensor in (key, value, gate, beta, a_log, dt_bias)
376 ):
377 raise ValueError("Fused KDA inputs must reside on the same NPU device.")
378 _require_fla_kda_runtime()
379
380
381def fused_chunk_kda(
382 query: torch.Tensor,
383 key: torch.Tensor,
384 value: torch.Tensor,
385 gate: torch.Tensor,
386 beta: torch.Tensor,
387 *,
388 a_log: torch.Tensor,
389 dt_bias: torch.Tensor,
390 scale: Optional[float] = None,
391 lower_bound: float = -5.0,
392 chunk_size: int = 64,
393 safe_gate: bool = True,
394 cu_seqlens: Optional[torch.Tensor] = None,
395) -> torch.Tensor:
396 """Run the local Triton-Ascend KDA backend without CP communication.
397
398 Args:
399 query: Local query tensor [B,T,H,K].
400 key: Matching local key tensor.
401 value: Local value tensor [B,T,HV,V].
402 gate: Per-token gate logits [B,T,HV,K].
403 beta: Per-token beta logits [B,T,HV].
404 a_log: Decay parameter with one value per value head.
405 dt_bias: Learned bias with one value per gate channel.
406 scale: Optional attention scaling factor.
407 lower_bound: Lower bound for the activated gate.
408 chunk_size: Tokens per local recurrence chunk.
409 safe_gate: Use the staged lower-bounded gate implementation.
410 """
411 validate_triton_kda_inputs(
412 query,
413 key,
414 value,
415 gate,
416 beta,
417 a_log,
418 dt_bias,
419 chunk_size=chunk_size,
420 lower_bound=lower_bound,
421 )
422 output, _ = run_fla_chunk_kda(
423 query,
424 key,
425 value,
426 gate,
427 beta,
428 a_log=a_log,
429 dt_bias=dt_bias.reshape(-1),
430 scale=scale,
431 lower_bound=lower_bound,
432 chunk_size=chunk_size,
433 safe_gate=safe_gate,
434 cu_seqlens=cu_seqlens,
435 )
436 return output
437
438
439def validate_kda_state_summary(state: torch.Tensor, matrix: torch.Tensor) -> None:
440 """Validate the fixed KDA affine contract before communication.
441
442 Args:
443 state: Nonempty FP32 S or G, shaped [B,H,128,128].
444 matrix: Matching FP32 transition on the same device.
445 """
446 if (state.ndim != 4 or state.shape[-2:] != (128, 128) or matrix.shape != state.shape
447 or state.shape[0] == 0 or state.shape[1] == 0):
448 raise ValueError("KDA state CP requires nonempty matching [B,H,128,128] summaries.")
449 if state.dtype != torch.float32 or matrix.dtype != torch.float32 or state.device != matrix.device:
450 raise ValueError("KDA state CP requires FP32 summaries on the same device.")
451 if state.device.type not in ("cpu", "npu"):
452 raise ValueError("KDA state CP supports CPU protocol checks and Ascend NPU execution only.")
453
454
455def _validate_prepared_summary_inputs(
456 key: torch.Tensor,
457 w: torch.Tensor,
458 u: torch.Tensor,
459 gate: torch.Tensor,
460 chunk_size: int,
461) -> tuple[int, int, int, int, int]:
462 """Validate the fixed Kimi K3 summary contract and return dimensions."""
463 if (key.ndim, w.ndim, u.ndim, gate.ndim) != (4, 4, 4, 4):
464 raise ValueError("KDA prepared summary expects rank-4 key/w/u/gate tensors.")
465 batch, sequence_length, heads, key_dim = key.shape
466 value_dim = u.shape[-1]
467 if key_dim != 128 or value_dim != 128 or chunk_size != 64:
468 raise NotImplementedError(
469 "Triton KDA state summary requires key_dim=value_dim=128 and "
470 "chunk_size=64."
471 )
472 if sequence_length <= 0:
473 raise ValueError("State summary requires a nonempty sample fragment.")
474 if w.shape != key.shape or gate.shape != key.shape:
475 raise ValueError(
476 "KDA prepared key, w, and gate must have identical shapes, got "
477 f"key={tuple(key.shape)}, w={tuple(w.shape)}, gate={tuple(gate.shape)}."
478 )
479 if u.shape[:3] != key.shape[:3]:
480 raise ValueError(
481 f"KDA prepared u prefix {tuple(u.shape[:3])} must match "
482 f"key prefix {tuple(key.shape[:3])}."
483 )
484 if not key.is_npu:
485 raise RuntimeError("Triton KDA state summary requires Ascend NPU tensors.")
486 return batch, sequence_length, heads, key_dim, value_dim
487
488
489def _validate_gradient_summary_inputs(
490 query: torch.Tensor,
491 key: torch.Tensor,
492 w: torch.Tensor,
493 gate: torch.Tensor,
494 grad_output: torch.Tensor,
495 grad_value: torch.Tensor,
496 chunk_size: int,
497) -> tuple[int, int, int, int, int]:
498 """Validate prepared tensors used by the reverse state wavefront."""
499 tensors = (query, key, w, gate, grad_output, grad_value)
500 if any(tensor.ndim != 4 for tensor in tensors):
501 raise ValueError(
502 "KDA gradient summary expects rank-4 query/key/w/gate/do/dv tensors."
503 )
504 batch, sequence_length, heads, key_dim = query.shape
505 value_dim = grad_output.shape[-1]
506 if key_dim != 128 or value_dim != 128 or chunk_size != 64:
507 raise NotImplementedError(
508 "Triton KDA state-gradient summary requires key_dim=value_dim=128 "
509 "and chunk_size=64."
510 )
511 if sequence_length <= 0:
512 raise ValueError("State summary requires a nonempty sample fragment.")
513 prepared_shape = (batch, sequence_length, heads, key_dim)
514 value_shape = (batch, sequence_length, heads, value_dim)
515 if key.shape != prepared_shape or w.shape != prepared_shape:
516 raise ValueError(
517 "KDA prepared query, key, and w must have identical shapes, got "
518 f"query={tuple(query.shape)}, key={tuple(key.shape)}, "
519 f"w={tuple(w.shape)}."
520 )
521 if gate.shape != prepared_shape:
522 raise ValueError(
523 f"KDA prepared gate shape {tuple(gate.shape)} must match "
524 f"query shape {prepared_shape}."
525 )
526 if grad_output.shape != value_shape or grad_value.shape != value_shape:
527 raise ValueError(
528 "KDA grad_output and grad_value must have shape "
529 f"{value_shape}, got do={tuple(grad_output.shape)}, "
530 f"dv={tuple(grad_value.shape)}."
531 )
532 if not query.is_npu:
533 raise RuntimeError(
534 "Triton KDA state-gradient summary requires Ascend NPU tensors."
535 )
536 return batch, sequence_length, heads, key_dim, value_dim
537
538
539def _launch_kda_state_summary(
540 key: torch.Tensor,
541 w: torch.Tensor,
542 u: torch.Tensor,
543 gate: torch.Tensor,
544 *,
545 chunk_size: int,
546 output_transition: bool = True,
547) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
548 """Launch the shared S/M summary used by the state CP protocols."""
549 return _launch_kda_paired_state_summary(
550 key,
551 w,
552 u,
553 gate,
554 chunk_size=chunk_size,
555 output_transition=output_transition,
556 )
557
558
559def _launch_kda_state_gradient_summary(
560 query: torch.Tensor,
561 key: torch.Tensor,
562 w: torch.Tensor,
563 gate: torch.Tensor,
564 grad_output: torch.Tensor,
565 grad_value: torch.Tensor,
566 scale: float,
567 *,
568 chunk_size: int,
569 block_size: int = 64,
570) -> torch.Tensor:
571 """Launch the reverse-wavefront Triton-Ascend summary kernel."""
572 # Triton is optional until a summary kernel is actually launched.
573 import triton # pylint: disable=import-outside-toplevel
574
575 from ._triton.kimi_delta_attention.state_summary import ( # pylint: disable=import-outside-toplevel
576 kda_state_grad_ext_kernel,
577 )
578
579 batch, sequence_length, heads, key_dim, value_dim = (
580 _validate_gradient_summary_inputs(
581 query,
582 key,
583 w,
584 gate,
585 grad_output,
586 grad_value,
587 chunk_size,
588 )
589 )
590 query, key, w, gate, grad_output, grad_value = (
591 tensor.contiguous()
592 for tensor in (query, key, w, gate, grad_output, grad_value)
593 )
594 grad_state_ext = torch.empty(
595 batch,
596 heads,
597 key_dim,
598 value_dim,
599 dtype=torch.float32,
600 device=query.device,
601 )
602 kda_state_grad_ext_kernel[
603 (triton.cdiv(value_dim, block_size), batch * heads)
604 ](
605 query,
606 key,
607 w,
608 gate,
609 grad_output,
610 grad_value,
611 grad_state_ext,
612 float(scale),
613 sequence_length,
614 H=heads,
615 H_TOTAL=heads,
616 HEAD_OFFSET=0,
617 K=key_dim,
618 V=value_dim,
619 BT=chunk_size,
620 BV=block_size,
621 num_warps=2,
622 )
623 return grad_state_ext
624
625
626@torch.compiler.disable
627def _launch_kda_paired_state_summary(
628 key: torch.Tensor,
629 w: torch.Tensor,
630 u: torch.Tensor,
631 gate: torch.Tensor,
632 *,
633 chunk_size: int = 64,
634 output_transition: bool = True,
635) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
636 """Build Ascend FLA-paired ``S_ext`` and an explicit FP32 transfer ``M``."""
637 # Triton is optional until a summary kernel is actually launched.
638 import triton # pylint: disable=import-outside-toplevel
639
640 from ._triton.kimi_delta_attention.state_summary import ( # pylint: disable=import-outside-toplevel
641 kda_split_state_summary_kernel,
642 kda_state_transition_kernel,
643 )
644
645 batch, sequence_length, heads, key_dim, value_dim = (
646 _validate_prepared_summary_inputs(key, w, u, gate, chunk_size)
647 )
648 key, w, u, gate = (
649 tensor.contiguous() for tensor in (key, w, u, gate)
650 )
651 state_ext = torch.empty(
652 batch,
653 heads,
654 key_dim,
655 value_dim,
656 dtype=torch.float32,
657 device=key.device,
658 )
659 transition = None
660 if output_transition:
661 transition = torch.empty(
662 batch,
663 heads,
664 key_dim,
665 key_dim,
666 dtype=torch.float32,
667 device=key.device,
668 )
669 kda_split_state_summary_kernel[(1, batch * heads)](
670 key,
671 w,
672 u,
673 gate,
674 state_ext,
675 transition if transition is not None else state_ext,
676 sequence_length,
677 H=heads,
678 H_TOTAL=heads,
679 HEAD_OFFSET=0,
680 K=key_dim,
681 V=value_dim,
682 BT=chunk_size,
683 BV=128,
684 OUTPUT_MODE=1,
685 num_warps=2,
686 )
687 if output_transition:
688 kda_state_transition_kernel[(triton.cdiv(key_dim, 64), batch * heads)](
689 key,
690 w,
691 gate,
692 transition,
693 sequence_length,
694 H=heads,
695 K=key_dim,
696 BT=chunk_size,
697 BV=64,
698 num_warps=4,
699 num_stages=2,
700 )
701 return state_ext, transition
702
703
704@torch.compiler.disable
705def kda_state_summary_forward_from_prepared(
706 key: torch.Tensor,
707 w: torch.Tensor,
708 u: torch.Tensor,
709 gate: torch.Tensor,
710 *,
711 chunk_size: int = 64,
712 output_transition: bool = True,
713) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
714 """Build the local affine summary for state context parallelism.
715
716 ``S_ext`` follows Ascend FLA h's FP32 feedback. ``M`` composes explicit
717 chunk transfers with FP32 feedback, following FLA CP.
718 ``output_transition=False`` returns only S and skips M allocation/computation.
719 It is valid for a zero-entry P2P endpoint whose backward never applies M.
720
721 Args:
722 key: Prepared keys, shaped [batch, tokens, heads, key_dim].
723 w: Prepared feedback weights with the same shape as key.
724 u: Prepared values, shaped [batch, tokens, heads, value_dim].
725 gate: Per-chunk cumulative log2 gates matching key.
726 chunk_size: Number of tokens per local chunk; the kernel requires 64.
727 output_transition: Whether the caller needs the local transition M.
728
729 Returns:
730 The FP32 state S and the FP32 transition M, or None when M is omitted.
731 """
732 return _launch_kda_state_summary(
733 key,
734 w,
735 u,
736 gate,
737 chunk_size=chunk_size,
738 output_transition=output_transition,
739 )
740
741
742@torch.compiler.disable
743def kda_state_gradient_summary_from_prepared(
744 query: torch.Tensor,
745 key: torch.Tensor,
746 w: torch.Tensor,
747 gate: torch.Tensor,
748 grad_output: torch.Tensor,
749 grad_value: torch.Tensor,
750 scale: float,
751 *,
752 chunk_size: int = 64,
753) -> torch.Tensor:
754 """Return the local-loss contribution to the incoming KDA state gradient.
755
756 Match Ascend FLA ``dhu`` at zero terminal state: scale ``grad_output``
757 before its dot-input cast and preserve the two K64 slabs and subtraction
758 grouping. This summary omits the full ``dh``/``dv`` outputs. All inputs
759 are read-only; the affine application to a nonzero state is a separate step.
760
761 Args:
762 query: Prepared gated queries [B,T,H,K].
763 key: Matching prepared gated keys.
764 w: Prepared feedback weights matching key.
765 gate: Per-chunk cumulative log2 gates matching key.
766 grad_output: Original token-output gradients [B,T,H,V].
767 grad_value: Local value gradients before recurrent feedback.
768 scale: Attention scaling factor.
769 chunk_size: Tokens per local chunk; the kernel requires 64.
770
771 Returns:
772 FP32 local contribution G, shaped [B,H,K,V].
773 """
774 return _launch_kda_state_gradient_summary(
775 query,
776 key,
777 w,
778 gate,
779 grad_output,
780 grad_value,
781 scale,
782 chunk_size=chunk_size,
783 block_size=128,
784 )
785
786
787def merge_affine_summaries(
788 states: torch.Tensor, matrices: torch.Tensor, rank: int, forward: bool,
789) -> torch.Tensor:
790 """Merge the exclusive prefix or transposed suffix in chronological order.
791
792 Args:
793 states: Affine offsets shaped [P,B,H,128,128].
794 matrices: Matching transfer matrices, possibly views of packed storage.
795 rank: Chronological rank whose input state or final-state gradient is requested.
796 forward: Select forward prefix instead of backward suffix.
797
798 Returns:
799 Contiguous FP32 recurrent state or state gradient shaped [B,H,128,128].
800 """
801 if states.ndim != 5 or states.shape != matrices.shape or states.shape[0] == 0:
802 raise ValueError("KDA merge requires matching rank-stacked summaries.")
803 size, batch, heads = states.shape[:3]
804 validate_kda_state_summary(states[0], matrices[0])
805 if not 0 <= rank < size:
806 raise ValueError("KDA merge rank is outside the summary group.")
807 if any(t.stride(1) != heads * t.stride(2) or t.stride(-1) != 1 for t in (states, matrices)):
808 raise ValueError("KDA merge requires consecutive batch/head slabs and columns.")
809 if states.device.type != "npu":
810 raise ValueError("KDA fused state merge requires Ascend NPU tensors.")
811 count = rank if forward else size - rank - 1
812 output = states.new_empty((batch, heads, 128, 128))
813 if count == 0:
814 return output.zero_()
815 # Triton is optional for imports; production merging requires Ascend.
816 # pylint: disable=import-outside-toplevel
817 from hyper_parallel.components.functional._triton.kimi_delta_attention.cp_merge import (
818 kda_cached_affine_merge_kernel,
819 )
820 # pylint: enable=import-outside-toplevel
821
822 kda_cached_affine_merge_kernel[(2, batch * heads)](
823 output, states, matrices, count, rank,
824 state_rank_stride=states.stride(0), state_head_stride=states.stride(2), state_row_stride=states.stride(3),
825 matrix_rank_stride=matrices.stride(0), matrix_head_stride=matrices.stride(2),
826 matrix_row_stride=matrices.stride(3),
827 forward=forward, block_v=64, num_warps=2, num_stages=2)
828 return output
829
830
831def _validate_scan_range(indices: range, size: int, forward: bool, prefix_count: int | None) -> None:
832 """Check the requested chronological interval and optional saved prefix."""
833 count = len(indices)
834 if prefix_count is not None and not 0 <= prefix_count <= count:
835 raise ValueError("The saved prefix must lie within the scan interval.")
836 if count:
837 endpoints_valid = all(0 <= index < size for index in (indices[0], indices[-1]))
838 if indices.step != (1 if forward else -1) or not endpoints_valid:
839 raise ValueError("KDA scans require an ordered interval inside the group.")
840
841
842def scan_kda_affine_maps(maps: torch.Tensor, incoming: torch.Tensor,
843 indices: range, forward: bool, prefix_count: int | None = None,
844 ) -> tuple[torch.Tensor, torch.Tensor | None]:
845 """Scan ordered group maps from a nonzero entry state.
846
847 Args:
848 maps: Rank-stacked S/M summaries in packed [P,B,H,128,256] layout.
849 incoming: Contiguous FP32 entry state.
850 indices: Contiguous chronological prefix or reverse suffix.
851 forward: Use forward maps or their transposed reverse application.
852 prefix_count: Optionally return the state after this many applications.
853
854 Returns:
855 The outgoing state and the optional saved intermediate prefix.
856 """
857 count = len(indices)
858 _validate_scan_range(indices, maps.shape[0], forward, prefix_count)
859 if not count:
860 return incoming, incoming if prefix_count == 0 else None
861 if incoming.device.type != "npu" or not incoming.is_contiguous():
862 raise ValueError("KDA fused scans require a contiguous Ascend input state.")
863 output = torch.empty_like(incoming)
864 prefix = None
865 if prefix_count is not None:
866 prefix = incoming if prefix_count == 0 else output if prefix_count == count else torch.empty_like(incoming)
867 save_prefix = prefix is not None and prefix_count not in (0, count)
868 # Keep the optional Triton dependency out of CPU-only model imports.
869 # pylint: disable=import-outside-toplevel
870 from hyper_parallel.components.functional._triton.kimi_delta_attention.cp_merge import kda_affine_scan_kernel
871 # pylint: enable=import-outside-toplevel
872
873 batch, heads = incoming.shape[:2]
874 kda_affine_scan_kernel[(2, batch * heads)](
875 output, prefix, maps, incoming, count, indices.start, prefix_count or 0,
876 rank_stride=maps.stride(0), head_stride=maps.stride(2), row_stride=maps.stride(3),
877 forward=forward, save_prefix=save_prefix, block_v=64, num_warps=2, num_stages=2)
878 return output, prefix