Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / kimi_delta_attention.py: 77%
275 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
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"""Local KDA math, state application and explicit backend selection."""
16from __future__ import annotations
17from collections.abc import Sequence
18from typing import Optional
20import torch
21from torch.nn import functional as F
23from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import packed_eager
24from .kimi_delta_attention_ascendc import ascendc_chunk_kda
25from .kimi_delta_attention_triton import fused_chunk_kda, is_fla_triton_kda_available
28def _validate_kda_inputs(
29 query: torch.Tensor,
30 key: torch.Tensor,
31 value: torch.Tensor,
32 gate: torch.Tensor,
33 beta: torch.Tensor,
34) -> tuple[int, int, int, int, int, int]:
35 """Validate dense token-first KDA inputs and return their dimensions."""
36 if (query.dim(), key.dim(), value.dim(), gate.dim()) != (4, 4, 4, 4):
37 raise ValueError("query, key, value, and gate must be rank-4 tensors.")
38 if beta.dim() != 3:
39 raise ValueError("beta must be a rank-3 tensor.")
40 if query.shape != key.shape:
41 raise ValueError("query and key must have identical shapes.")
43 batch_size, sequence_length, num_k_heads, k_head_dim = query.shape
44 value_batch, value_sequence, num_v_heads, v_head_dim = value.shape
45 if (value_batch, value_sequence) != (batch_size, sequence_length):
46 raise ValueError("value batch and sequence dimensions must match query.")
47 if gate.shape != (batch_size, sequence_length, num_v_heads, k_head_dim):
48 raise ValueError(
49 "gate must have shape [B, S, num_v_heads, k_head_dim], got "
50 f"{tuple(gate.shape)}."
51 )
52 if beta.shape != (batch_size, sequence_length, num_v_heads):
53 raise ValueError(
54 "beta must have shape [B, S, num_v_heads], got "
55 f"{tuple(beta.shape)}."
56 )
57 if num_v_heads % num_k_heads != 0:
58 raise ValueError("num_v_heads must be divisible by num_k_heads.")
59 return (
60 batch_size,
61 sequence_length,
62 num_k_heads,
63 num_v_heads,
64 k_head_dim,
65 v_head_dim,
66 )
69def _reshape_gate_bias(
70 parameter: torch.Tensor,
71 num_v_heads: int,
72 k_head_dim: int,
73 name: str,
74) -> torch.Tensor:
75 """Return a gate parameter as ``[num_v_heads, k_head_dim]``."""
76 if parameter.numel() != num_v_heads * k_head_dim:
77 raise ValueError(
78 f"{name} must contain {num_v_heads * k_head_dim} elements, "
79 f"got {parameter.numel()}."
80 )
81 return parameter.reshape(num_v_heads, k_head_dim)
84def torch_kda_gate(
85 gate_logits: torch.Tensor,
86 a_log: torch.Tensor,
87 dt_bias: torch.Tensor,
88 *,
89 lower_bound: Optional[float] = None,
90) -> torch.Tensor:
91 """Activate KDA log-decay logits.
93 ``lower_bound`` selects the Kimi K3 parameterization
94 ``g_min * sigmoid(exp(a_log) * (logits + bias))``. With no lower bound,
95 this function implements the earlier Kimi Linear negative-Softplus gate.
97 Args:
98 gate_logits: Untransformed per-key decay logits.
99 a_log: Log decay-rate parameter.
100 dt_bias: Per-key time-step bias.
101 lower_bound: Negative lower bound of the safe decay gate.
102 """
103 if gate_logits.dim() != 4:
104 raise ValueError("gate_logits must have shape [B, S, H, K].")
105 num_v_heads, k_head_dim = gate_logits.shape[-2:]
106 if a_log.numel() != num_v_heads:
107 raise ValueError(
108 f"a_log must contain {num_v_heads} elements, got {a_log.numel()}."
109 )
110 bias = _reshape_gate_bias(dt_bias, num_v_heads, k_head_dim, "dt_bias")
111 scale = a_log.float().exp().reshape(1, 1, num_v_heads, 1)
112 preactivation = gate_logits.float() + bias.float().reshape(
113 1, 1, num_v_heads, k_head_dim
114 )
115 if lower_bound is None:
116 return -scale * F.softplus(preactivation) # pylint: disable=not-callable
117 if lower_bound >= 0:
118 raise ValueError(f"lower_bound must be negative, got {lower_bound}.")
119 return float(lower_bound) * torch.sigmoid(scale * preactivation)
122def _prepare_kda_inputs(
123 query: torch.Tensor,
124 key: torch.Tensor,
125 value: torch.Tensor,
126 gate: torch.Tensor,
127 beta: torch.Tensor,
128 *,
129 a_log: Optional[torch.Tensor],
130 dt_bias: Optional[torch.Tensor],
131 scale: Optional[float],
132 use_qk_l2norm_in_kernel: bool,
133 use_gate_in_kernel: bool,
134 use_beta_sigmoid_in_kernel: bool,
135 lower_bound: Optional[float],
136) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, float]:
137 """Apply the common KDA input transformations in FP32."""
138 _, _, num_k_heads, num_v_heads, k_head_dim, _ = _validate_kda_inputs(
139 query, key, value, gate, beta
140 )
141 if use_qk_l2norm_in_kernel:
142 query = query * torch.rsqrt(
143 (query.float() * query.float()).sum(dim=-1, keepdim=True) + 1e-6
144 ).to(query.dtype)
145 key = key * torch.rsqrt(
146 (key.float() * key.float()).sum(dim=-1, keepdim=True) + 1e-6
147 ).to(key.dtype)
148 if use_gate_in_kernel:
149 if a_log is None or dt_bias is None:
150 raise ValueError("a_log and dt_bias are required when gate activation is enabled.")
151 gate = torch_kda_gate(
152 gate,
153 a_log,
154 dt_bias,
155 lower_bound=lower_bound,
156 )
157 if use_beta_sigmoid_in_kernel:
158 beta = beta.float().sigmoid()
160 value_groups = num_v_heads // num_k_heads
161 query = query.float().repeat_interleave(value_groups, dim=2)
162 key = key.float().repeat_interleave(value_groups, dim=2)
163 value = value.float()
164 gate = gate.float()
165 beta = beta.float()
166 effective_scale = k_head_dim ** -0.5 if scale is None else scale
167 return query, key, value, gate, beta, float(effective_scale)
170def _initial_kda_state(
171 value: torch.Tensor,
172 k_head_dim: int,
173 initial_state: Optional[torch.Tensor],
174) -> torch.Tensor:
175 """Build or validate a KDA state in FP32."""
176 expected_shape = (value.shape[0], value.shape[2], k_head_dim, value.shape[3])
177 if initial_state is None:
178 return value.new_zeros(expected_shape, dtype=torch.float32)
179 if tuple(initial_state.shape) != expected_shape:
180 raise ValueError(
181 f"initial_state must have shape {expected_shape}, got "
182 f"{tuple(initial_state.shape)}."
183 )
184 return initial_state.float()
187def torch_recurrent_kda(
188 query: torch.Tensor,
189 key: torch.Tensor,
190 value: torch.Tensor,
191 gate: torch.Tensor,
192 beta: torch.Tensor,
193 *,
194 a_log: Optional[torch.Tensor] = None,
195 dt_bias: Optional[torch.Tensor] = None,
196 scale: Optional[float] = None,
197 initial_state: Optional[torch.Tensor] = None,
198 output_final_state: bool = False,
199 use_qk_l2norm_in_kernel: bool = False,
200 use_gate_in_kernel: bool = False,
201 use_beta_sigmoid_in_kernel: bool = False,
202 lower_bound: Optional[float] = None,
203) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
204 """Evaluate the exact token-recurrent KDA equations with eager ops.
206 Args:
207 query: Query tensor in batch, token, head, key-dimension order.
208 key: Key tensor with the same token and key-head axes as query.
209 value: Value tensor in batch, token, head, value-dimension order.
210 gate: Decay gate or output gate required by this stage.
211 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
212 a_log: Log decay-rate parameter.
213 dt_bias: Per-key time-step bias.
214 scale: Query scaling factor; None selects the head-dimension default.
215 initial_state: Optional state entering the first local chunk.
216 output_final_state: Whether to return the state after the final chunk.
217 use_qk_l2norm_in_kernel: Whether this operator normalizes query and key.
218 use_gate_in_kernel: Whether this operator transforms raw decay logits.
219 use_beta_sigmoid_in_kernel: Whether this operator transforms beta logits with sigmoid.
220 lower_bound: Negative lower bound of the safe decay gate.
221 """
222 output_dtype = value.dtype
223 query, key, value, gate, beta, scale = _prepare_kda_inputs(
224 query,
225 key,
226 value,
227 gate,
228 beta,
229 a_log=a_log,
230 dt_bias=dt_bias,
231 scale=scale,
232 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
233 use_gate_in_kernel=use_gate_in_kernel,
234 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
235 lower_bound=lower_bound,
236 )
237 state = _initial_kda_state(value, key.shape[-1], initial_state)
238 outputs = []
239 for token_idx in range(query.shape[1]):
240 query_i = query[:, token_idx]
241 key_i = key[:, token_idx]
242 value_i = value[:, token_idx]
243 gate_i = gate[:, token_idx]
244 beta_i = beta[:, token_idx]
246 state = state * gate_i.exp().unsqueeze(-1)
247 state_value = torch.einsum("bhk,bhkv->bhv", key_i, state)
248 residual = value_i - state_value
249 state = state + torch.einsum(
250 "bhk,bhv->bhkv",
251 key_i * beta_i.unsqueeze(-1),
252 residual,
253 )
254 outputs.append(torch.einsum("bhk,bhkv->bhv", query_i * scale, state))
256 output = torch.stack(outputs, dim=1).to(output_dtype)
257 return output, state if output_final_state else None
260def _inverse_unit_lower_triangular(strict_lower: torch.Tensor) -> torch.Tensor:
261 """Invert ``I + strict_lower`` using differentiable forward substitution."""
262 chunk_size = strict_lower.shape[-1]
263 rows = []
264 for row_idx in range(chunk_size):
265 base = -strict_lower[..., row_idx, :]
266 if rows:
267 previous = torch.stack(rows, dim=-2)
268 row = torch.einsum(
269 "...i,...ij->...j",
270 base[..., :row_idx],
271 previous,
272 )
273 else:
274 row = torch.zeros_like(base)
275 diagonal = F.one_hot( # pylint: disable=not-callable
276 torch.tensor(row_idx, device=strict_lower.device),
277 num_classes=chunk_size,
278 ).to(strict_lower.dtype)
279 rows.append(row + diagonal)
280 return torch.stack(rows, dim=-2)
283def _prepare_kda_wy(
284 query: torch.Tensor,
285 key: torch.Tensor,
286 value: torch.Tensor,
287 gate: torch.Tensor,
288 beta: torch.Tensor,
289 chunk_size: int,
290) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
291 """Build the cumulative gate, causal mask, and chunkwise WY factors."""
292 gate = gate.cumsum(dim=-2)
293 causal = torch.ones(
294 chunk_size,
295 chunk_size,
296 dtype=torch.bool,
297 device=query.device,
298 ).tril()
299 strict_causal = causal.logical_xor(
300 torch.eye(chunk_size, dtype=torch.bool, device=query.device)
301 )
303 gate_pair = gate.unsqueeze(-2) - gate.unsqueeze(-3)
304 key_pair = torch.einsum(
305 "...ik,...jk,...ijk->...ij",
306 key,
307 key,
308 gate_pair.exp(),
309 )
310 strict_lower = (
311 key_pair * beta.unsqueeze(-1)
312 ).masked_fill(~strict_causal, 0)
313 inverse = _inverse_unit_lower_triangular(strict_lower)
314 transform = inverse * beta.unsqueeze(-2)
315 w = transform @ (key * gate.exp())
316 u = transform @ value
318 return gate, causal, w, u
321def _run_kda_chunks(
322 query: torch.Tensor,
323 key: torch.Tensor,
324 gate: torch.Tensor,
325 w: torch.Tensor,
326 u: torch.Tensor,
327 state: torch.Tensor,
328 causal: torch.Tensor,
329 scale: float,
330 num_chunks: int,
331) -> tuple[list[torch.Tensor], torch.Tensor]:
332 """Apply chunk WY factors to the recurrent state in sequence order."""
333 output_chunks = []
334 for chunk_idx in range(num_chunks):
335 query_i = query[:, :, chunk_idx]
336 key_i = key[:, :, chunk_idx]
337 gate_i = gate[:, :, chunk_idx]
338 w_i = w[:, :, chunk_idx]
339 u_i = u[:, :, chunk_idx]
341 relative_gate = gate_i.unsqueeze(-2) - gate_i.unsqueeze(-3)
342 qk = torch.einsum(
343 "bhik,bhjk,bhijk->bhij",
344 query_i,
345 key_i,
346 relative_gate.exp(),
347 ).masked_fill(~causal, 0)
348 value_new = u_i - w_i @ state
349 output_inter = (query_i * gate_i.exp()) @ state
350 output_chunks.append(output_inter * scale + qk @ value_new * scale)
352 last_gate = gate_i[:, :, -1]
353 key_decay = key_i * (last_gate.unsqueeze(-2) - gate_i).exp()
354 state = state * last_gate.exp().unsqueeze(-1)
355 state = state + key_decay.transpose(-1, -2) @ value_new
357 return output_chunks, state
360def torch_chunk_kda(
361 query: torch.Tensor,
362 key: torch.Tensor,
363 value: torch.Tensor,
364 gate: torch.Tensor,
365 beta: torch.Tensor,
366 *,
367 a_log: Optional[torch.Tensor] = None,
368 dt_bias: Optional[torch.Tensor] = None,
369 scale: Optional[float] = None,
370 initial_state: Optional[torch.Tensor] = None,
371 output_final_state: bool = False,
372 use_qk_l2norm_in_kernel: bool = False,
373 use_gate_in_kernel: bool = False,
374 use_beta_sigmoid_in_kernel: bool = False,
375 lower_bound: Optional[float] = None,
376 chunk_size: int = 64,
377 cu_seqlens: Optional[torch.Tensor] = None,
378) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
379 """Evaluate chunkwise KDA using the UT/WY representation.
381 This implementation is algebraically independent from
382 :func:`torch_recurrent_kda`; comparing the two catches errors in the
383 chunk transform that a second token loop would hide.
385 Args:
386 query: Query tensor in batch, token, head, key-dimension order.
387 key: Key tensor with the same token and key-head axes as query.
388 value: Value tensor in batch, token, head, value-dimension order.
389 gate: Decay gate or output gate required by this stage.
390 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
391 a_log: Log decay-rate parameter.
392 dt_bias: Per-key time-step bias.
393 scale: Query scaling factor; None selects the head-dimension default.
394 initial_state: Optional state entering the first local chunk.
395 output_final_state: Whether to return the state after the final chunk.
396 use_qk_l2norm_in_kernel: Whether this operator normalizes query and key.
397 use_gate_in_kernel: Whether this operator transforms raw decay logits.
398 use_beta_sigmoid_in_kernel: Whether this operator transforms beta logits with sigmoid.
399 lower_bound: Negative lower bound of the safe decay gate.
400 chunk_size: Number of tokens in a recurrence chunk.
401 cu_seqlens: Cumulative document boundaries for packed tokens.
402 """
403 if cu_seqlens is not None:
404 return packed_eager(
405 torch_chunk_kda, (query, key, value, gate, beta), cu_seqlens,
406 initial_state=initial_state, output_final_state=output_final_state,
407 a_log=a_log, dt_bias=dt_bias, scale=scale,
408 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, use_gate_in_kernel=use_gate_in_kernel,
409 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel, lower_bound=lower_bound, chunk_size=chunk_size,
410 )
411 if chunk_size <= 0:
412 raise ValueError(f"chunk_size must be positive, got {chunk_size}.")
413 output_dtype = value.dtype
414 sequence_length = query.shape[1]
415 query, key, value, gate, beta, scale = _prepare_kda_inputs(
416 query,
417 key,
418 value,
419 gate,
420 beta,
421 a_log=a_log,
422 dt_bias=dt_bias,
423 scale=scale,
424 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
425 use_gate_in_kernel=use_gate_in_kernel,
426 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
427 lower_bound=lower_bound,
428 )
429 batch_size, _, num_heads, k_head_dim = query.shape
430 v_head_dim = value.shape[-1]
431 pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
432 query = F.pad(query, (0, 0, 0, 0, 0, pad_size))
433 key = F.pad(key, (0, 0, 0, 0, 0, pad_size))
434 value = F.pad(value, (0, 0, 0, 0, 0, pad_size))
435 gate = F.pad(gate, (0, 0, 0, 0, 0, pad_size))
436 beta = F.pad(beta, (0, 0, 0, pad_size))
437 num_chunks = query.shape[1] // chunk_size
439 def chunk_view(tensor: torch.Tensor) -> torch.Tensor:
440 """Rearrange a token-first tensor to head-first chunks.
442 Args:
443 tensor: Tensor to reshape or redistribute without changing token order.
444 """
445 shape = tensor.shape
446 return tensor.reshape(
447 shape[0], num_chunks, chunk_size, shape[2], *shape[3:]
448 ).permute(0, 3, 1, 2, *range(4, tensor.dim() + 1))
450 query, key, value, gate, beta = [
451 chunk_view(tensor) for tensor in (query, key, value, gate, beta)
452 ]
453 gate, causal, w, u = _prepare_kda_wy(query, key, value, gate, beta, chunk_size)
455 state = _initial_kda_state(
456 value.permute(0, 2, 3, 1, 4).reshape(
457 batch_size, num_chunks * chunk_size, num_heads, v_head_dim
458 ),
459 k_head_dim,
460 initial_state,
461 )
462 output_chunks, state = _run_kda_chunks(query, key, gate, w, u, state, causal, scale, num_chunks)
464 output = torch.stack(output_chunks, dim=2)
465 output = output.permute(0, 2, 3, 1, 4).reshape(
466 batch_size,
467 num_chunks * chunk_size,
468 num_heads,
469 v_head_dim,
470 )
471 output = output[:, :sequence_length].to(output_dtype)
472 return output, state if output_final_state else None
475def _chunk_kda_summary_inputs(
476 key: torch.Tensor,
477 value: torch.Tensor,
478 gate: torch.Tensor,
479 beta: torch.Tensor,
480 chunk_size: int,
481) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int]:
482 """Pad and convert token-first KDA tensors into head-first chunks."""
483 sequence_length = key.shape[1]
484 pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
485 key = F.pad(key, (0, 0, 0, 0, 0, pad_size))
486 value = F.pad(value, (0, 0, 0, 0, 0, pad_size))
487 gate = F.pad(gate, (0, 0, 0, 0, 0, pad_size))
488 beta = F.pad(beta, (0, 0, 0, pad_size))
489 num_chunks = key.shape[1] // chunk_size
491 def chunk_view(tensor: torch.Tensor) -> torch.Tensor:
492 """Rearrange one token-first tensor to head-first chunks.
494 Args:
495 tensor: Tensor to reshape or redistribute without changing token order.
496 """
497 shape = tensor.shape
498 return tensor.reshape(
499 shape[0], num_chunks, chunk_size, shape[2], *shape[3:]
500 ).permute(0, 3, 1, 2, *range(4, tensor.dim() + 1))
502 key, value, gate, beta = (
503 chunk_view(tensor) for tensor in (key, value, gate, beta)
504 )
505 return key, value, gate, beta, num_chunks
508def torch_kda_state_summary(
509 query: torch.Tensor,
510 key: torch.Tensor,
511 value: torch.Tensor,
512 gate: torch.Tensor,
513 beta: torch.Tensor,
514 *,
515 a_log: Optional[torch.Tensor] = None,
516 dt_bias: Optional[torch.Tensor] = None,
517 scale: Optional[float] = None,
518 use_qk_l2norm_in_kernel: bool = False,
519 use_gate_in_kernel: bool = False,
520 use_beta_sigmoid_in_kernel: bool = False,
521 lower_bound: Optional[float] = None,
522 chunk_size: int = 64,
523) -> tuple[torch.Tensor, torch.Tensor]:
524 """Summarize a local KDA segment as ``H_out = M @ H_in + S``.
526 The implementation follows the same chunkwise WY equations as
527 :func:`torch_chunk_kda`, but computes only the state-independent affine
528 transition. ``S`` has shape ``[B, HV, K, V]`` and ``M`` has shape
529 ``[B, HV, K, K]``. Query is accepted to share KDA input preprocessing and
530 grouped-value validation; the state transition itself is independent of
531 query and output scale.
533 Args:
534 query: Query tensor in batch, token, head, key-dimension order.
535 key: Key tensor with the same token and key-head axes as query.
536 value: Value tensor in batch, token, head, value-dimension order.
537 gate: Decay gate or output gate required by this stage.
538 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
539 a_log: Log decay-rate parameter.
540 dt_bias: Per-key time-step bias.
541 scale: Query scaling factor; None selects the head-dimension default.
542 use_qk_l2norm_in_kernel: Whether this operator normalizes query and key.
543 use_gate_in_kernel: Whether this operator transforms raw decay logits.
544 use_beta_sigmoid_in_kernel: Whether this operator transforms beta logits with sigmoid.
545 lower_bound: Negative lower bound of the safe decay gate.
546 chunk_size: Number of tokens in a recurrence chunk.
547 """
548 if chunk_size <= 0:
549 raise ValueError(f"chunk_size must be positive, got {chunk_size}.")
550 _, key, value, gate, beta, _ = _prepare_kda_inputs(
551 query, key, value, gate, beta,
552 a_log=a_log,
553 dt_bias=dt_bias,
554 scale=scale,
555 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
556 use_gate_in_kernel=use_gate_in_kernel,
557 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
558 lower_bound=lower_bound,
559 )
560 key, value, gate, beta, num_chunks = _chunk_kda_summary_inputs(
561 key, value, gate, beta, chunk_size,
562 )
563 gate = gate.cumsum(dim=-2)
564 strict_causal = torch.ones(
565 chunk_size, chunk_size, dtype=torch.bool, device=key.device,
566 ).tril(diagonal=-1)
567 gate_pair = gate.unsqueeze(-2) - gate.unsqueeze(-3)
568 key_pair = torch.einsum(
569 "...ik,...jk,...ijk->...ij", key, key, gate_pair.exp(),
570 )
571 strict_lower = (key_pair * beta.unsqueeze(-1)).masked_fill(
572 ~strict_causal,
573 0,
574 )
575 inverse = _inverse_unit_lower_triangular(strict_lower)
576 transform = inverse * beta.unsqueeze(-2)
577 w = transform @ (key * gate.exp())
578 u = transform @ value
580 batch_size, num_heads, _, _, k_head_dim = key.shape
581 v_head_dim = value.shape[-1]
582 eye = torch.eye(
583 k_head_dim, dtype=torch.float32, device=key.device,
584 ).reshape(1, 1, k_head_dim, k_head_dim)
585 state_ext = torch.zeros(
586 batch_size,
587 num_heads,
588 k_head_dim,
589 v_head_dim,
590 dtype=torch.float32,
591 device=key.device,
592 )
593 transition = eye.expand(batch_size, num_heads, -1, -1).clone()
595 for chunk_idx in range(num_chunks):
596 key_i = key[:, :, chunk_idx]
597 gate_i = gate[:, :, chunk_idx]
598 w_i = w[:, :, chunk_idx]
599 u_i = u[:, :, chunk_idx]
600 last_gate = gate_i[:, :, -1]
601 key_decay = key_i * (last_gate.unsqueeze(-2) - gate_i).exp()
602 transition_i = torch.diag_embed(last_gate.exp())
603 transition_i = transition_i - key_decay.transpose(-1, -2) @ w_i
604 state_ext_i = key_decay.transpose(-1, -2) @ u_i
605 state_ext = transition_i @ state_ext + state_ext_i
606 transition = transition_i @ transition
608 return state_ext.float(), transition.float()
611def torch_apply_kda_state_summary(
612 state_ext: torch.Tensor,
613 transition: torch.Tensor,
614 initial_state: Optional[torch.Tensor],
615) -> torch.Tensor:
616 """Apply a KDA affine state summary to an incoming state.
618 Args:
619 state_ext: State produced from a zero initial state.
620 transition: Linear state transition matrix.
621 initial_state: Optional state entering the first local chunk.
622 """
623 if initial_state is None:
624 return state_ext.float()
625 return (transition @ initial_state.to(transition) + state_ext).float()
628def torch_compose_kda_state_summaries(
629 first_state_ext: torch.Tensor,
630 first_transition: torch.Tensor,
631 second_state_ext: torch.Tensor,
632 second_transition: torch.Tensor,
633) -> tuple[torch.Tensor, torch.Tensor]:
634 """Compose two chronological KDA summaries, first then second.
636 Args:
637 first_state_ext: Zero-input state of the earlier sequence interval.
638 first_transition: Transition matrix of the earlier sequence interval.
639 second_state_ext: Zero-input state of the later sequence interval.
640 second_transition: Transition matrix of the later sequence interval.
641 """
642 state_ext = second_transition @ first_state_ext + second_state_ext
643 transition = second_transition @ first_transition
644 return state_ext, transition
647def apply_kda_state_summary(
648 state_ext: torch.Tensor,
649 transition: Optional[torch.Tensor],
650 initial_state: Optional[torch.Tensor],
651) -> torch.Tensor:
652 """Apply a prepared KDA state summary in FP32.
654 Args:
655 state_ext: Local zero-entry state S.
656 transition: Local transfer M; may be omitted for a zero entry.
657 initial_state: Incoming FP32 state, or None for a zero entry.
659 Returns:
660 The outgoing FP32 state.
661 """
662 if initial_state is None:
663 return state_ext
664 # Model autocast must not silently quantize a communicated FP32 state.
665 with torch.autocast(device_type=state_ext.device.type, enabled=False):
666 return torch.matmul(transition.float(), initial_state.float()) + state_ext
669def apply_kda_state_gradient_summary(
670 grad_state_ext: torch.Tensor,
671 transition: torch.Tensor,
672 grad_final_state: Optional[torch.Tensor],
673) -> torch.Tensor:
674 """Apply the adjoint summary to a gradient from the next rank.
676 Args:
677 grad_state_ext: Local gradient contribution G.
678 transition: Forward transfer M used by this backend's existing adjoint.
679 grad_final_state: Incoming terminal-state gradient, or None for zero exit.
680 """
681 if grad_final_state is None:
682 return grad_state_ext
683 with torch.autocast(device_type=grad_state_ext.device.type, enabled=False):
684 return (
685 torch.matmul(transition.float().transpose(-2, -1), grad_final_state.float())
686 + grad_state_ext
687 )
690_KDA_BACKENDS = frozenset({"eager", "triton", "ascendc"})
691_TRITON_KDA_HEAD_DIM = 128
692_TRITON_KDA_CHUNK_SIZE = 64
695def _has_triton_kda_shapes(
696 query: torch.Tensor,
697 value: torch.Tensor,
698 gate: torch.Tensor,
699 beta: torch.Tensor,
700 a_log: torch.Tensor,
701 dt_bias: torch.Tensor,
702 chunk_size: int,
703) -> bool:
704 """Check the fixed dense shapes accepted by the Triton KDA path."""
705 batch_size, sequence_length, num_query_heads, key_dim = query.shape
706 num_value_heads, value_dim = value.shape[2:]
707 return all((
708 value.shape[:2] == (batch_size, sequence_length),
709 gate.shape == (batch_size, sequence_length, num_value_heads, key_dim),
710 beta.shape == (batch_size, sequence_length, num_value_heads),
711 num_value_heads % num_query_heads == 0,
712 a_log.numel() == num_value_heads,
713 dt_bias.numel() == num_value_heads * key_dim,
714 key_dim == value_dim == _TRITON_KDA_HEAD_DIM,
715 chunk_size == _TRITON_KDA_CHUNK_SIZE,
716 ))
719def _is_triton_kda_input_supported(
720 query: torch.Tensor,
721 key: Optional[torch.Tensor],
722 value: Optional[torch.Tensor],
723 gate: Optional[torch.Tensor],
724 beta: Optional[torch.Tensor],
725 a_log: Optional[torch.Tensor],
726 dt_bias: Optional[torch.Tensor],
727 *,
728 chunk_size: int,
729 lower_bound: Optional[float],
730) -> bool:
731 """Check the fixed Kimi K3 contract validated by the fused backend."""
732 operands = (key, value, gate, beta, a_log, dt_bias)
733 if any(tensor is None for tensor in operands):
734 return False
735 if lower_bound is None:
736 return False
738 basic_contract = (
739 query.device.type == "npu",
740 all(tensor.dtype == torch.bfloat16 for tensor in (query, key, value, gate, beta)),
741 all(tensor.dtype == torch.float32 for tensor in (a_log, dt_bias)),
742 all(tensor.ndim == 4 for tensor in (query, key, value, gate)),
743 beta.ndim == 3,
744 query.shape == key.shape,
745 )
746 if not all(basic_contract):
747 return False
749 shape_supported = _has_triton_kda_shapes(
750 query, value, gate, beta, a_log, dt_bias, chunk_size,
751 )
752 lower_bound_supported = -5.0 <= lower_bound < 0
753 if not (shape_supported and lower_bound_supported):
754 return False
755 return all(tensor.device == query.device for tensor in operands)
758def is_triton_kda_available(
759 query: Optional[torch.Tensor] = None,
760 key: Optional[torch.Tensor] = None,
761 value: Optional[torch.Tensor] = None,
762 gate: Optional[torch.Tensor] = None,
763 beta: Optional[torch.Tensor] = None,
764 a_log: Optional[torch.Tensor] = None,
765 dt_bias: Optional[torch.Tensor] = None,
766 *,
767 chunk_size: int = _TRITON_KDA_CHUNK_SIZE,
768 lower_bound: Optional[float] = -5.0,
769) -> bool:
770 """Return whether the validated Triton-Ascend KDA backend is available.
772 Args:
773 query: Query tensor in batch, token, head, key-dimension order.
774 key: Key tensor with the same token and key-head axes as query.
775 value: Value tensor in batch, token, head, value-dimension order.
776 gate: Decay gate or output gate required by this stage.
777 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
778 a_log: Log decay-rate parameter.
779 dt_bias: Per-key time-step bias.
780 chunk_size: Number of tokens in a recurrence chunk.
781 lower_bound: Negative lower bound of the safe decay gate.
782 """
783 if chunk_size != _TRITON_KDA_CHUNK_SIZE:
784 return False
785 if query is not None and not _is_triton_kda_input_supported(
786 query,
787 key,
788 value,
789 gate,
790 beta,
791 a_log,
792 dt_bias,
793 chunk_size=chunk_size,
794 lower_bound=lower_bound,
795 ):
796 return False
797 return is_fla_triton_kda_available()
800def _normalize_kda_backend(backend: str) -> str:
801 """Normalize the selected backend and reject unsupported names."""
802 backend = backend.lower()
803 if backend not in _KDA_BACKENDS:
804 raise ValueError(
805 f"unsupported KDA backend {backend!r}; "
806 f"expected one of {sorted(_KDA_BACKENDS)}."
807 )
808 return backend
811def _validate_fused_state_contract(initial_state, output_final_state, qk_norm, gate, beta, backend) -> None:
812 """Keep raw-input dispatch separate from the stateful CP backend contract."""
813 if initial_state is not None or output_final_state:
814 raise NotImplementedError(
815 f"KDA backend={backend!r} currently supports zero initial state without "
816 "returning a final state; stateful execution is owned by the CP backend."
817 )
818 if not (qk_norm and gate and beta):
819 raise NotImplementedError(
820 f"KDA backend={backend!r} requires fused Q/K normalization, gate activation, "
821 "and beta sigmoid."
822 )
825def chunk_kda(
826 query: torch.Tensor,
827 key: torch.Tensor,
828 value: torch.Tensor,
829 gate: torch.Tensor,
830 beta: torch.Tensor,
831 *,
832 a_log: Optional[torch.Tensor] = None,
833 dt_bias: Optional[torch.Tensor] = None,
834 scale: Optional[float] = None,
835 initial_state: Optional[torch.Tensor] = None,
836 output_final_state: bool = False,
837 use_qk_l2norm_in_kernel: bool = False,
838 use_gate_in_kernel: bool = False,
839 use_beta_sigmoid_in_kernel: bool = False,
840 lower_bound: Optional[float] = None,
841 chunk_size: int = 64,
842 backend: str = "eager",
843 cu_seqlens: Optional[torch.Tensor | Sequence[int]] = None,
844) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
845 """Dispatch dense or packed KDA to the explicitly selected local backend.
847 Args:
848 query: Query tensor in batch, token, head, key-dimension order.
849 key: Key tensor with the same token and key-head axes as query.
850 value: Value tensor in batch, token, head, value-dimension order.
851 gate: Decay gate or output gate required by this stage.
852 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
853 a_log: Log decay-rate parameter.
854 dt_bias: Per-key time-step bias.
855 scale: Query scaling factor; None selects the head-dimension default.
856 initial_state: Optional state entering the first local chunk.
857 output_final_state: Whether to return the state after the final chunk.
858 use_qk_l2norm_in_kernel: Whether this operator normalizes query and key.
859 use_gate_in_kernel: Whether this operator transforms raw decay logits.
860 use_beta_sigmoid_in_kernel: Whether this operator transforms beta logits with sigmoid.
861 lower_bound: Negative lower bound of the safe decay gate.
862 chunk_size: Number of tokens in a recurrence chunk.
863 backend: Explicit local operator implementation to dispatch.
864 cu_seqlens: Cumulative document boundaries for packed tokens.
865 """
866 if query.ndim == 3:
867 output, final = chunk_kda(
868 *(tensor.unsqueeze(0) for tensor in (query, key, value, gate, beta)),
869 a_log=a_log, dt_bias=dt_bias, scale=scale, initial_state=initial_state,
870 output_final_state=output_final_state, use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
871 use_gate_in_kernel=use_gate_in_kernel, use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
872 lower_bound=lower_bound, chunk_size=chunk_size, backend=backend, cu_seqlens=cu_seqlens)
873 return output.squeeze(0), final
874 backend = _normalize_kda_backend(backend)
875 if backend == "eager":
876 return torch_chunk_kda(
877 query, key, value, gate, beta,
878 a_log=a_log,
879 dt_bias=dt_bias,
880 scale=scale,
881 initial_state=initial_state,
882 output_final_state=output_final_state,
883 use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
884 use_gate_in_kernel=use_gate_in_kernel,
885 use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
886 lower_bound=lower_bound,
887 chunk_size=chunk_size,
888 cu_seqlens=cu_seqlens,
889 )
890 _validate_fused_state_contract(initial_state, output_final_state, use_qk_l2norm_in_kernel,
891 use_gate_in_kernel, use_beta_sigmoid_in_kernel, backend)
892 if backend == "ascendc":
893 output = ascendc_chunk_kda(
894 query, key, value, gate, beta,
895 a_log=a_log.float() if a_log is not None else None,
896 dt_bias=dt_bias.float() if dt_bias is not None else None,
897 scale=scale, lower_bound=lower_bound, chunk_size=chunk_size, cu_seqlens=cu_seqlens,
898 )
899 return output, None
900 triton_a_log = a_log.float() if a_log is not None else None
901 triton_dt_bias = dt_bias.float() if dt_bias is not None else None
902 if not _is_triton_kda_input_supported(
903 query, key, value, gate, beta, triton_a_log, triton_dt_bias,
904 chunk_size=chunk_size,
905 lower_bound=lower_bound,
906 ):
907 raise RuntimeError(
908 "KDA backend='triton' received an unsupported input contract; it requires "
909 "q/k/v/gate/beta=bf16, a_log/dt_bias=fp32, "
910 "head_k_dim=head_v_dim=128, chunk_size=64, and a supported safe gate."
911 )
914 output = fused_chunk_kda(
915 query, key, value, gate, beta,
916 a_log=triton_a_log,
917 dt_bias=triton_dt_bias,
918 scale=scale,
919 lower_bound=lower_bound,
920 chunk_size=chunk_size,
921 safe_gate=True,
922 cu_seqlens=cu_seqlens,
923 )
924 return output, None