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"""Optional native local KDA phases and autograd for dense/packed inputs."""
16
17from __future__ import annotations
18
19import importlib
20import inspect
21from collections.abc import Sequence
22from functools import lru_cache
23from typing import Any, NamedTuple
24
25import torch
26from torch.autograd.function import once_differentiable
27
28from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import local_chunk_metadata
29
30
31@lru_cache(maxsize=1)
32def load_kda_native_ops() -> Any:
33 """Keep the optional native runtime out of ordinary framework imports."""
34 try:
35 ops = importlib.import_module("fla_npu.ops.ascendc")
36 except ImportError as error:
37 raise RuntimeError("backend='ascendc' requires a compatible fla-npu installation.") from error
38 required = {
39 "chunk_kda_fwd_prepare": ("backward_mode", "use_qk_l2norm_in_kernel", "use_beta_sigmoid_in_kernel"),
40 "chunk_fwd_h": ("output_final_state", "cu_seqlens", "chunk_indices"),
41 "chunk_kda_fwd_finalize": ("output_layout", "cu_seqlens", "chunk_indices"),
42 "chunk_kda_bwd_prepare": ("scale", "layout", "cu_seqlens", "chunk_indices"),
43 "chunk_kda_bwd_recompute": ("A_log", "dt_bias", "cu_seqlens", "chunk_indices", "input_layout"),
44 "chunk_gated_delta_rule_bwd_dhu": ("gK", "dht", "cu_seqlens", "chunk_indices"),
45 "chunk_kda_bwd_finalize": ("q_rstd", "k_rstd", "use_beta_sigmoid_in_kernel", "output_layout"),
46 }
47 for name, parameters in required.items():
48 operation = getattr(ops, name, None)
49 try:
50 signature = inspect.signature(operation)
51 except (TypeError, ValueError) as error:
52 raise RuntimeError(f"fla-npu lacks a compatible public {name} API.") from error
53 missing = set(parameters).difference(signature.parameters)
54 if missing:
55 raise RuntimeError(
56 f"fla-npu {name} lacks required parameters {sorted(missing)}; "
57 "install a fla-npu version providing these public KDA parameters."
58 )
59 return ops
60
61
62class KDANativePrepared(NamedTuple):
63 """Public Prepare slots in the native ABI order; omitted recomputable slots may be None."""
64
65 gk: torch.Tensor | None # FP32 chunk-local cumulative log2 decay.
66 aqk: torch.Tensor # Intra-chunk QK coefficients.
67 akk: torch.Tensor # Triangular KK coefficients for backward.
68 w: torch.Tensor | None # WY state-feedback coefficients.
69 u: torch.Tensor | None # Forward-only residual input to FwdH.
70 qg: torch.Tensor | None # Gated queries consumed by backward.
71 kg: torch.Tensor | None # Gated keys consumed by FwdH and backward.
72 qg_scaled: torch.Tensor | None # Forward-only queries including attention scale.
73 q_hat: torch.Tensor # Normalized head-major queries.
74 k_hat: torch.Tensor # Normalized head-major keys.
75 q_rstd: torch.Tensor # FP32 Q normalization auxiliary.
76 k_rstd: torch.Tensor # FP32 K normalization auxiliary.
77 beta_eff: torch.Tensor # FP32 head-major sigmoid(beta) cache.
78
79
80def prepare_kda_native(inputs: tuple[torch.Tensor, ...], scale: float, lower_bound: float,
81 metadata: dict) -> KDANativePrepared:
82 """Prepare once for native summaries and the local state recurrence.
83
84 Args:
85 inputs: Token-major raw Q/K/V/gate/beta and FP32 A_log/dt_bias.
86 scale: Attention output scale.
87 lower_bound: Safe gate lower bound.
88 metadata: Local cu_seqlens and chunk_indices, or empty for dense input.
89
90 Returns:
91 Native recompute-mode tensors in ABI order; the forward-unused qg slot is None.
92 """
93 ops = load_kda_native_ops()
94 query, key, value, gate, beta, a_log, dt_bias = inputs
95 result = ops.chunk_kda_fwd_prepare(
96 query, key, value, gate, beta,
97 scale, layout="BSND", chunk_size=64,
98 safe_gate=True, lower_bound=lower_bound, use_gate_in_kernel=True,
99 A_log=a_log, dt_bias=dt_bias.flatten(), epsilon=1e-6,
100 use_qk_l2norm_in_kernel=True, use_beta_sigmoid_in_kernel=True,
101 use_exp2=True, backward_mode="recompute", **metadata,
102 )
103 if len(result) != 13 or any(
104 not isinstance(tensor, torch.Tensor) for index, tensor in enumerate(result) if index != 5):
105 raise RuntimeError("fla-npu Prepare must return native-norm recompute slots; only qg may be omitted.")
106 return KDANativePrepared(*result)
107
108
109def _native_backward_view(tensor: torch.Tensor, packed: bool) -> torch.Tensor:
110 """Expose packed NTD views without copying the B=1 Prepare/FwdH storage."""
111 return tensor.squeeze(0) if packed else tensor
112
113
114def ascendc_chunk_kda(
115 query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
116 gate: torch.Tensor, beta: torch.Tensor, *, a_log: torch.Tensor,
117 dt_bias: torch.Tensor, scale: float | None = None, lower_bound: float = -5.0,
118 chunk_size: int = 64, cu_seqlens: Sequence[int] | torch.Tensor | None = None,
119) -> torch.Tensor:
120 """Run dense or packed KDA with native attention and paired raw-input gradients.
121
122 Args:
123 query: Raw BF16 queries [B,T,H,128] or packed [T,H,128].
124 key: Raw BF16 keys with the same shape.
125 value: BF16 values with the same shape.
126 gate: BF16 or FP32 gate logits with the same shape.
127 beta: BF16 or FP32 beta logits [B,T,H] or packed [T,H].
128 a_log: FP32 decay parameters with H elements.
129 dt_bias: FP32 gate bias with H*128 elements.
130 scale: Positive attention scale, default 1/sqrt(128).
131 lower_bound: Safe gate lower bound in [-5,0).
132 chunk_size: Must be 64 for this native kernel family.
133 cu_seqlens: Strictly increasing host offsets for packed inputs, including
134 zero and T. Packed rank-four inputs require B=1. Documents need not
135 be multiples of 64; zero-length documents are rejected.
136
137 Returns:
138 BF16 output with the query shape. External recurrent states and double
139 backward are not exposed. Native Q/K norm auxiliaries remain saved;
140 native capability checks select the supported device implementation.
141 """
142 if query.ndim == 3:
143 if cu_seqlens is None:
144 raise ValueError("Packed TND inputs require cu_seqlens.")
145 return ascendc_chunk_kda(
146 *(tensor.unsqueeze(0) for tensor in (query, key, value, gate, beta)),
147 a_log=a_log, dt_bias=dt_bias, scale=scale, lower_bound=lower_bound,
148 chunk_size=chunk_size, cu_seqlens=cu_seqlens).squeeze(0)
149 if query.ndim != 4:
150 raise ValueError("KDA inputs must have shape [B,T,H,K] or packed [T,H,K].")
151 if chunk_size != 64:
152 raise ValueError("Ascend C KDA uses chunk_size=64.")
153 metadata = local_chunk_metadata(cu_seqlens, query.shape[1])
154 if metadata and query.shape[0] != 1:
155 raise ValueError("Packed Ascend C KDA requires B=1.")
156 scale = query.shape[-1] ** -0.5 if scale is None else float(scale)
157 tokens = tuple(tensor.contiguous() for tensor in (query, key, value))
158 # Gate/beta stay token-major for backward. Native operators validate their
159 # dtype, shape and device; only adapter-owned layout/metadata checks live here.
160 # Clone sliced parameters to give native tiling this shard's storage descriptor.
161 return _AscendCKDAStages.apply(
162 *tokens, gate.contiguous(), beta.contiguous(), a_log.reshape(-1).clone(),
163 dt_bias.reshape(-1, query.shape[-1]).clone(), scale, lower_bound, metadata)
164
165
166def finish_kda_native_forward(ctx: Any, inputs: tuple[torch.Tensor, ...], prepared: KDANativePrepared,
167 initial: torch.Tensor | None, scale: float, lower_bound: float,
168 metadata: dict, *, compress_entry: bool = False) -> torch.Tensor:
169 """Apply the incoming state, finalize outputs and retain the inputs for backward recomputation.
170
171 Args:
172 ctx: Invocation-owned autograd context receiving saved tensors.
173 inputs: Raw tensors previously passed to prepare_kda_native.
174 prepared: Native Prepare results for these inputs.
175 initial: Incoming recurrent state, or None for zero entry.
176 scale: Attention output scale.
177 lower_bound: Safe gate lower bound retained for backward.
178 metadata: Local packed indices, or an empty dense descriptor.
179 compress_entry: Keep only the first external entry for a contiguous packed CP interval.
180 Dense batches packed locally require all sample entries and leave this false.
181 """
182 ops = load_kda_native_ops()
183 _, _, value, gate, _, a_log, dt_bias = inputs
184 hidden, v_new, _ = ops.chunk_fwd_h(
185 prepared.kg, prepared.w, prepared.u, gk=prepared.gk, initial_state=initial,
186 output_final_state=False, use_exp2=True, **metadata)
187 output = ops.chunk_kda_fwd_finalize(
188 prepared.qg_scaled, prepared.aqk, v_new, hidden, output_layout="BSND", **metadata)
189 prepared = prepared._replace(gk=None, w=None, u=None, qg=None, kg=None, qg_scaled=None)
190 # Only a contiguous global packed interval has zero entries after its first
191 # fragment. Locally packed dense samples can each inherit a nonzero state.
192 ctx.initial_count = initial.shape[0] if compress_entry and initial is not None else 0
193 entry = initial[:1].clone() if ctx.initial_count > 1 else initial
194 ctx.save_for_backward(value, gate, a_log, dt_bias, *prepared, entry)
195 ctx.dtypes = tuple(tensor.dtype for tensor in inputs)
196 ctx.scale, ctx.lower_bound, ctx.native_metadata = scale, lower_bound, metadata
197 return output
198
199
200def restore_kda_native_backward(ctx: Any, saved_tensors: tuple) -> tuple:
201 """Rebuild WY and local states from the saved entry without state communication.
202
203 Args:
204 ctx: Forward context with scale, gate bound and packed metadata.
205 saved_tensors: One unpack of saved base inputs, Prepare coefficients and entry H.
206
207 Returns:
208 Head-major V/gate, prepared tensors and h/v_new for the native backward.
209 V/gate layouts are reused by finalize rather than converted a second time.
210 """
211 ops = load_kda_native_ops()
212 value, gate, a_log, dt_bias = saved_tensors[:4]
213 prepared = KDANativePrepared(*saved_tensors[4:-1])
214 entry = saved_tensors[-1]
215 value_head, gate_head = (tensor.transpose(1, 2).contiguous() for tensor in (value, gate))
216 gk, weights, updates, query_gated, key_gated = ops.chunk_kda_bwd_recompute(
217 prepared.q_hat, prepared.k_hat, value_head, gate_head, prepared.beta_eff, prepared.akk, 64,
218 A_log=a_log, dt_bias=dt_bias, use_gate_in_kernel=True, use_exp2=True,
219 lower_bound=ctx.lower_bound, input_layout="BNSD", **ctx.native_metadata)
220 initial = entry
221 if ctx.initial_count > 1:
222 initial = entry.new_zeros((ctx.initial_count, *entry.shape[1:]))
223 initial[:1].copy_(entry)
224 hidden, v_new, _ = ops.chunk_fwd_h(
225 key_gated, weights, updates, gk=gk, initial_state=initial,
226 output_final_state=False, use_exp2=True, **ctx.native_metadata)
227 prepared = prepared._replace(gk=gk, w=weights, qg=query_gated, kg=key_gated)
228 return value_head, gate_head, a_log, dt_bias, *prepared, hidden, v_new
229
230
231def prepare_kda_native_backward(ctx: Any, saved_tensors: tuple, grad_output: torch.Tensor) -> tuple:
232 """Prepare local gradients independently of the terminal state gradient.
233
234 Args:
235 ctx: Forward context containing scale and local document metadata.
236 saved_tensors: The single unpack of ctx.saved_tensors, shared with finalize.
237 grad_output: Token-major output gradient.
238
239 Returns:
240 Head-major dO and the native dAqk, local dV and raw dQ intermediates.
241 """
242 ops = load_kda_native_ops()
243 prepared = KDANativePrepared(*saved_tensors[4:-2])
244 hidden, v_new = saved_tensors[-2:]
245 packed = bool(ctx.native_metadata)
246
247 grad = grad_output.transpose(1, 2).contiguous()
248 d_aqk, dv_local, dq_raw = ops.chunk_kda_bwd_prepare(
249 *(_native_backward_view(tensor, packed) for tensor in (prepared.aqk, v_new, grad, hidden)), scale=ctx.scale,
250 layout="NTD" if packed else "BNSD", chunk_size=64, **ctx.native_metadata)
251 dv_local_head = dv_local.unsqueeze(0) if packed else dv_local
252 return grad, d_aqk, dv_local_head, dq_raw
253
254
255def finish_kda_native_backward(ctx: Any, saved_tensors: tuple, grad: torch.Tensor, d_aqk: torch.Tensor,
256 dv_local_head: torch.Tensor, dq_raw: torch.Tensor,
257 terminal: torch.Tensor | None) -> tuple:
258 """Apply dHT and finish native Q/K/V, raw gate and sigmoid gradients.
259
260 Args:
261 ctx: Forward context containing metadata, scale and original input dtypes.
262 saved_tensors: The reconstructed tuple used by backward prepare, including head-major V/gate.
263 grad: Head-major output gradient.
264 d_aqk: Native intra-chunk coefficient gradient.
265 dv_local_head: Head-major local value gradient before state feedback.
266 dq_raw: Native raw query-gradient intermediate.
267 terminal: Terminal recurrent-state gradient, or None for zero exit.
268
269 Returns:
270 Seven input gradients, cast to their original dtypes.
271 """
272 ops = load_kda_native_ops()
273 value, gate, a_log, dt_bias, *saved = saved_tensors
274 (gk, _, akk, weights, _, qg, kg, _, query, key,
275 query_rstd, key_rstd, beta, hidden, v_new) = saved
276 packed = bool(ctx.native_metadata)
277
278 hidden_grad, _, dv_scan = ops.chunk_gated_delta_rule_bwd_dhu(
279 qg, kg, weights, grad, dv_local_head, ctx.scale, 64,
280 gK=gk, h0=None, dht=terminal, use_exp2=True, **ctx.native_metadata)
281 dq, dk, dv, dbeta, dgate, da_log, ddt_bias = ops.chunk_kda_bwd_finalize(
282 *(_native_backward_view(tensor, packed)
283 for tensor in (query, key, value, gk, gate, beta)),
284 a_log, dt_bias,
285 *(_native_backward_view(tensor, packed) for tensor in (akk, v_new, hidden, hidden_grad, dv_scan)),
286 d_aqk, dq_raw,
287 scale=ctx.scale, lower_bound=ctx.lower_bound,
288 q_rstd=_native_backward_view(query_rstd, packed),
289 k_rstd=_native_backward_view(key_rstd, packed),
290 use_beta_sigmoid_in_kernel=False,
291 output_layout="TND" if packed else "BSND", **ctx.native_metadata)
292 if packed:
293 dq, dk, dv, dbeta, dgate = (tensor.unsqueeze(0) for tensor in (dq, dk, dv, dbeta, dgate))
294 # Keep gradients token-major for projection/accumulation consumers.
295 # Reuse Prepare's FP32 sigmoid cache through a matching layout view.
296 dbeta = torch.ops.aten.sigmoid_backward.default(dbeta, beta.transpose(1, 2))
297 gradients = (dq, dk, dv, dgate, dbeta, da_log, ddt_bias.reshape_as(dt_bias))
298 return tuple(gradient.to(dtype) for gradient, dtype in zip(gradients, ctx.dtypes))
299
300
301class _AscendCKDAStages(torch.autograd.Function):
302 """Native local KDA autograd, without communication resources or protocol callbacks."""
303
304 @staticmethod
305 def forward(ctx: Any, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
306 gate: torch.Tensor, beta: torch.Tensor, a_log: torch.Tensor, dt_bias: torch.Tensor,
307 scale: float, lower_bound: float, metadata: dict) -> torch.Tensor:
308 """Prepare and execute a local sequence with a zero entry state.
309
310 Args:
311 ctx: Autograd context owned by this invocation.
312 query: Token-major raw queries.
313 key: Token-major raw keys.
314 value: Token-major values.
315 gate: Raw gate logits or output-gate values for this stage.
316 beta: Raw delta-rule sigmoid logits.
317 a_log: FP32 logarithmic decay-rate parameters.
318 dt_bias: FP32 per-channel decay bias.
319 scale: Attention output scaling factor.
320 lower_bound: Lower bound of the safe decay gate.
321 metadata: Native packed-document offsets and chunk indices.
322 """
323 inputs = (query, key, value, gate, beta, a_log, dt_bias)
324 prepared = prepare_kda_native(inputs, scale, lower_bound, metadata)
325 return finish_kda_native_forward(ctx, inputs, prepared, None, scale, lower_bound, metadata)
326
327 @staticmethod
328 @once_differentiable
329 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
330 """Compute local gradients with a zero terminal state gradient.
331
332 Args:
333 ctx: Autograd context owned by this invocation.
334 grad_output: Gradient of the local output.
335 """
336 # Unpack once: non-reentrant checkpoint hooks consume saved tensors.
337 saved = restore_kda_native_backward(ctx, ctx.saved_tensors)
338 prepared = prepare_kda_native_backward(ctx, saved, grad_output)
339 gradients = finish_kda_native_backward(ctx, saved, *prepared, None)
340 return (*gradients, None, None, None)