Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/functional/gated_delta_net.py 63.1% 160-162,177-178,193-198,209-211,221-222,246-248,251-263,303,320-324,326-329,332,340,344
hyper_parallel/components/functional/gated_delta_net_ascendc.py 50.0% 155
hyper_parallel/components/functional/gated_delta_net_triton.py 0.0% 23-24,26-27,29,32-38,41-43,46,64-65,73-74,82,85,107,119,141,153,179,187,197,207,210,238,246,256,265,268,296,311,347,361,372-376,383,386,416,429,442,459,462-464,488-489,491-495,497,505,518-520,542,554-556,578,590-592,618,639,649,659,672-674,702,717-719,747,762-764,810,827-833,838-839,842-844,884,897,910,932,935,938-941,971,984-991,993-996,1008-1013,1027,1030-1031,1081-1082,1086-1087,1090-1091,1095-1096,1100-1101,1107-1109,1113-1114,1118-1119,1121-1123,1125,1128,1131,1136-1137,1143-1144,1172-1182,1188-1189,1197,1213-1217,1220,1230-1237,1240,1246,1249-1250,1276,1280,1283,1291,1308
hyper_parallel/components/functional/kimi_delta_attention.py 77.2% 37,39,41,46,48,53,77,104,107,116,118,150,180,412,549,624,662-663,665-666,681-684,705-707,732-736,738,746-747,749,752-755,783-785,796-797,804,813-814,818-819,867,873,890,892-893,899-902,907,914,924
hyper_parallel/components/functional/kimi_delta_attention_ascendc.py 15.6% 92,104,151,178-180,183,185,187-190,204-207,209-210,213-214,234-236,238,240,243,254-255,258-261,287-288,300-303
hyper_parallel/components/functional/kimi_delta_attention_triton.py 27.2% 61-65,68-69,73,77-78,82-85,94-97,102-106,109-110,117,131-134,148,156-157,162-167,171-175,180-184,191-192,273-274,303-319,347,350,354-358,361-369,373-374,407,418,432,459-464,468-471,475-476,480-482,495-497,500-503,507-512,517-518,522-523,528-529,532,545,569,571,575,586,590,598,619,634,636,641,644,647,655-657,665,683-684,697,728,770,797-810,813,818,824,829-835,853-863,866,869-870,874
hyper_parallel/components/functional/linear_attention_convolution.py 79.8% 39,41,44,46,138-139,141,200,209,357,364,369,372,374,412,421-422
hyper_parallel/components/modules/attention/gated_delta_net/__init__.py 100%  
hyper_parallel/components/modules/attention/gated_delta_net/cp_gated_delta_net.py 22.6% 54,73,83-95,99-102,104-107,110-113,116-122,124,135-144,146-147,150-155,160,165,172,175-180,185-188,190-193,198,200-203,210,213-214,235,273,278-284,289,291-292,300,304,310,315-317,319-320,331-342,353,356,360,371-374,376-379,384,390-391,404-407,411-414,416-419,424,430-433,435,439,444-446,473-474,485,487-490,493
hyper_parallel/components/modules/attention/gated_delta_net/gated_delta_net.py 87.8% 71,83,86,88,90,128,171,179-187,268,301,304-306
hyper_parallel/components/modules/attention/gated_delta_net/gated_delta_net_family.py 95.3% 38,51
hyper_parallel/components/modules/attention/kimi_delta_attention/__init__.py 100%  
hyper_parallel/components/modules/attention/kimi_delta_attention/cp_kimi_delta_attention.py 24.5% 64,89,99-109,111-120,125-128,130,132,135-138,155-159,161-163,165-167,170-172,174-178,182-194,197,199-201,212-229,233-237,259,261,282-305,311-314,323,335-337,351,354-355,370,373-374,385,396-401,415,418-426,428-435,450,453-467,485,496-497,503,525-529,535-538,542,544,547-548,551-553,555-565,567-569,575-580,582-583,587-599,601-603,642-645,647,651,653,655-658,663-670,672,677-678,681-682,687-688,691-693,695-698,700,704-718,731,735,737,741-753,755-758,762,764-765,769,772,776,780,784-785,791-792,800-801,807-811,814,816-817,820-825,827,882,895-898,900-901
hyper_parallel/components/modules/attention/kimi_delta_attention/cp_recursive_doubling.py 89.1% 36,44-45,82,198,208,253,259-260,284,286-289
hyper_parallel/components/modules/attention/kimi_delta_attention/cp_state_ascendc.py 17.1% 37-38,42-45,50-54,68-77,87-96,104-107,116-123,133,147-169,172-174,178-201,206-212,217-221,223,226-228,230-231,258-264,266-268,270-279,290,292-296,298-303,334-344
hyper_parallel/components/modules/attention/kimi_delta_attention/kimi_delta_attention.py 84.3% 86,106,108,110,112,132,136,138,140,142,174-175,186,188,190,200,219,223-232,273,357,359,361
hyper_parallel/components/modules/attention/kimi_delta_attention/kimi_delta_attention_family.py 90.6% 40,43,45,47,64,150
hyper_parallel/components/modules/attention/linear_attention_utils/cp_convolution.py 23.8% 48,51-55,59-60,65-66,70,76-77,97-98,100-104,106-109,111,113-115,117,123-125
hyper_parallel/components/modules/attention/linear_attention_utils/layer_adapter.py 79.7% 41,52-53,69,74,77,92,100,117,120,123,125
hyper_parallel/components/modules/attention/linear_attention_utils/parallel_layout.py 82.9% 45,71-73,84-85
hyper_parallel/components/modules/attention/linear_attention_utils/sequence_layout.py 46.2% 314-318,323,348,380-385,387
hyper_parallel/distributed/_builder/family_layout.py 66.7% 146
hyper_parallel/distributed/context_parallel/collectives.py 3.0% 833-835,837-839,844-847,849-856,858-860,867-873,875-878
hyper_parallel/components/functional/gated_delta_net.py
156
157
158
159
160
161
162
163
164
165
166
        state_ext: Local zero-entry state S.
        transition: Local transfer M, omitted only for a zero entry.
        initial_state: Incoming state, or None for a zero entry.
    """
    if initial_state is None:
        return state_ext
    return torch.matmul(transition, initial_state.float()) + state_ext


def apply_gdn_state_gradient_summary(
    grad_state_ext: torch.Tensor,
173
174
175
176
177
178
179
180
181
182
        grad_state_ext: Local gradient contribution G.
        transition: Forward transfer M used by this backend's existing adjoint.
        grad_final_state: Incoming terminal-state gradient, or None for zero exit.
    """
    if grad_final_state is None:
        return grad_state_ext
    return (
        torch.matmul(transition.transpose(-2, -1), grad_final_state.float())
        + grad_state_ext
    )
189
190
191
192
193
194
195
196
197
198
199
200
201
202


def _parse_version(version_text: str) -> tuple[int, int, int]:
    """Return a three-component numeric version tuple."""
    parts = []
    for part in version_text.split("+")[0].split(".")[:3]:
        match = re.match(r"\d+", part)
        if match is not None:
            parts.append(int(match.group()))
    return tuple((parts + [0, 0, 0])[:3])


def _is_triton_gdn_input_supported(
    query: torch.Tensor,
205
206
207
208
209
210
211
212
213
214
215
    g: Optional[torch.Tensor],
    beta: Optional[torch.Tensor],
) -> bool:
    """Check the fixed Qwen3.5 GDN contract validated by this backend."""
    if any(tensor is None for tensor in (key, value, g, beta)):
        return False
    if not (
        query.device.type == "npu"
        and query.dtype == key.dtype == value.dtype == beta.dtype == torch.bfloat16
        and g.dtype == torch.float32
        and query.ndim == key.ndim == value.ndim == 4
217
218
219
220
221
222
223
224
225
        and query.shape == key.shape
        and query.shape[:3] == value.shape[:3] == g.shape == beta.shape
        and query.shape[-1] == value.shape[-1] == _TRITON_GDN_HEAD_DIM
    ):
        return False
    return all(
        tensor.device == query.device
        for tensor in (key, value, g, beta)
    )
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
        g: Log decay values for the recurrence.
        beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
        chunk_size: Number of tokens in a recurrence chunk.
    """
    if chunk_size != _TRITON_GDN_CHUNK_SIZE:
        return False
    if query is not None and not _is_triton_gdn_input_supported(
        query, key, value, g, beta,
    ):
        return False
    try:
        version_text = importlib.metadata.version("triton-ascend")
    except importlib.metadata.PackageNotFoundError:
        return False
    version = _parse_version(version_text)
    if version < _MIN_TRITON_ASCEND_VERSION:
        return False
    try:
        importlib.import_module("triton")
        return importlib.util.find_spec("triton.backends.ascend") is not None
    except (AttributeError, ImportError, ModuleNotFoundError):
        return False


def chunk_gated_delta_rule(
    query: torch.Tensor,
299
300
301
302
303
304
305
306
307
            backend=backend, cu_seqlens=cu_seqlens)
        return output.squeeze(0), final
    backend = backend.lower()
    if backend not in _GDN_BACKENDS:
        raise ValueError(
            f"unsupported GDN backend {backend!r}; "
            f"expected one of {sorted(_GDN_BACKENDS)}."
        )
    if backend == "eager":
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
            output_final_state=output_final_state,
            normalize_qk=use_qk_l2norm_in_kernel,
            cu_seqlens=cu_seqlens,
        )
    if backend == "ascendc":
        if initial_state is not None or output_final_state:
            raise NotImplementedError("GDN Ascend C currently supports zero-state local or pure Ulysses training only.")
        if chunk_size != 64:
            raise ValueError("GDN Ascend C requires chunk_size=64.")
        # Preserve the existing GDN normalization graph outside the native core.
        if use_qk_l2norm_in_kernel:
            query, key = _l2norm(query), _l2norm(key)
        return chunk_gated_delta_rule_ascendc(query, key, value, g, beta, cu_seqlens=cu_seqlens)
    if not is_triton_gdn_available(
        query, key, value, g, beta, chunk_size=chunk_size,
    ):
        raise RuntimeError(
            "GDN backend='triton' requires triton-ascend >= 3.2.1 "
            "installation with the Ascend backend and NPU inputs "
            "q/k/v/beta=bf16, g=fp32, head_k_dim=head_v_dim=128, "
            "and chunk_size=64."
336
337
338
339
340
341
342
343
344
345
346
347
348
            "and chunk_size=64."
        )

    # The vendored Triton kernels are an optional NPU dependency.
    from hyper_parallel.components.functional.gated_delta_net_triton import (  # pylint: disable=import-outside-toplevel
        chunk_gated_delta_rule as triton_chunk_gated_delta_rule,
    )

    return triton_chunk_gated_delta_rule(
        query,
        key,
        value,
        g,
hyper_parallel/components/functional/gated_delta_net_ascendc.py
151
152
153
154
155
156
    if query.ndim != 4:
        raise ValueError("GDN inputs must have shape [B,T,H,K].")
    if cu_seqlens is not None and query.shape[0] != 1:
        raise ValueError("Packed Ascend C GDN requires physical batch size one.")
    metadata = local_chunk_metadata(cu_seqlens, query.shape[1])
    return _AscendCGDN.apply(query, key, value, g, beta, metadata), None
hyper_parallel/components/functional/gated_delta_net_triton.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# pylint: disable=non-google-docstring,disallowed-name,unused-argument,invalid-name
# pylint: disable=missing-module-docstring,missing-function-docstring
# pylint: disable=abstract-method,arguments-differ

import warnings
from typing import Any, Optional

import torch
import triton

from ._triton.gated_delta_net.state_summary import (
    gdn_packed_state_summary_kernel, gdn_state_grad_ext_kernel,
)
from ._triton.gated_delta_net.chunk_delta_h import chunk_gated_delta_rule_bwd_dhu, chunk_gated_delta_rule_fwd_h
from ._triton.gated_delta_net.chunk_o import chunk_bwd_dqkwg, chunk_bwd_dv_local, chunk_fwd_o
from ._triton.gated_delta_net.chunk_scaled_dot_kkt import chunk_scaled_dot_kkt_fwd
from ._triton.gated_delta_net.cumsum import chunk_local_cumsum
from ._triton.gated_delta_net.solve_tril import solve_tril
from ._triton.gated_delta_net.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
from ._triton.gated_delta_net.wy_fast import prepare_wy_repr_bwd, recompute_w_u_fwd


def _l2norm(x: torch.Tensor, eps: float = 1e-6) -> tuple[torch.Tensor, torch.Tensor]:
    inv_norm = torch.rsqrt((x * x).sum(dim=-1, keepdim=True) + eps)
    return (x * inv_norm).to(x.dtype), inv_norm


def chunk_gated_delta_rule_fwd_prepare(
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
        beta: torch.Tensor,
60
61
62
63
64
65
66
67
68
69
        beta: Activated delta-rule update weights.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    g = chunk_local_cumsum(g, chunk_size=chunk_size, cu_seqlens=cu_seqlens, head_first=False)
    matrix_a = chunk_scaled_dot_kkt_fwd(
        k=k,
        g=g,
        beta=beta,
        cu_seqlens=cu_seqlens,
69
70
71
72
73
74
75
76
77
78
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
        output_dtype=torch.float32,
    )
    matrix_a = solve_tril(A=matrix_a, cu_seqlens=cu_seqlens, output_dtype=k.dtype)
    w, u = recompute_w_u_fwd(
        k=k,
        v=v,
        beta=beta,
        A=matrix_a,
78
79
80
81
82
83
84
85
86
87
88
89
        A=matrix_a,
        g=g,
        cu_seqlens=cu_seqlens,
    )
    return g, matrix_a, w, u


def chunk_gated_delta_rule_fwd_apply_state(
        k: torch.Tensor,
        g: torch.Tensor,
        w: torch.Tensor,
        u: torch.Tensor,
103
104
105
106
107
108
109
110
111
        output_final_state: Whether to return the terminal state.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    return chunk_gated_delta_rule_fwd_h(
        k=k,
        w=w,
        u=u,
        g=g,
115
116
117
118
119
120
121
122
123
        cu_seqlens=cu_seqlens,
    )


def chunk_gated_delta_rule_fwd_output(
        q: torch.Tensor,
        k: torch.Tensor,
        v_new: torch.Tensor,
        h: torch.Tensor,
137
138
139
140
141
142
143
144
145
        scale: Attention output scaling factor.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    return chunk_fwd_o(
        q=q,
        k=k,
        v=v_new,
        h=h,
149
150
151
152
153
154
155
156
157
        chunk_size=chunk_size,
    )


def chunk_gated_delta_rule_fwd(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
175
176
177
178
179
180
181
182
183
        output_final_state: Whether to return the terminal state.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    g, matrix_a, w, u = chunk_gated_delta_rule_fwd_prepare(
        k=k,
        v=v,
        g=g,
        beta=beta,
183
184
185
186
187
188
189
190
191
        beta=beta,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    h, v_new, final_state = chunk_gated_delta_rule_fwd_apply_state(
        k=k,
        g=g,
        w=w,
        u=u,
193
194
195
196
197
198
199
200
201
        output_final_state=output_final_state,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    output = chunk_gated_delta_rule_fwd_output(
        q=q,
        k=k,
        v_new=v_new,
        h=h,
203
204
205
206
207
208
209
210
211
212
213
214
        scale=scale,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    return g, output, matrix_a, final_state


def chunk_gated_delta_rule_bwd_prepare(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
234
235
236
237
238
239
240
241
242
        do: Gradient of the local output.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    w, u = recompute_w_u_fwd(
        k=k,
        v=v,
        beta=beta,
        A=A,
242
243
244
245
246
247
248
249
250
        A=A,
        g=g,
        cu_seqlens=cu_seqlens,
    )
    h, v_new, _ = chunk_gated_delta_rule_fwd_apply_state(
        k=k,
        g=g,
        w=w,
        u=u,
252
253
254
255
256
257
258
259
260
        output_final_state=False,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dv = chunk_bwd_dv_local(
        q=q,
        k=k,
        g=g,
        do=do,
261
262
263
264
265
266
267
268
269
270
271
272
        scale=scale,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    return w, h, v_new, dv


def chunk_gated_delta_rule_bwd_state(
        q: torch.Tensor,
        k: torch.Tensor,
        w: torch.Tensor,
        g: torch.Tensor,
292
293
294
295
296
297
298
299
300
        scale: Attention output scaling factor.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    return chunk_gated_delta_rule_bwd_dhu(
        q=q,
        k=k,
        w=w,
        g=g,
307
308
309
310
311
312
313
314
315
        chunk_size=chunk_size,
    )


def chunk_gated_delta_rule_bwd_finish(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
343
344
345
346
347
348
349
350
351
        scale: Attention output scaling factor.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    dq, dk, dw, dg = chunk_bwd_dqkwg(
        q=q,
        k=k,
        v=v_new,
        w=w,
357
358
359
360
361
362
363
364
365
        chunk_size=chunk_size,
        scale=scale,
        cu_seqlens=cu_seqlens,
    )
    dk2, dv, db, dg2 = prepare_wy_repr_bwd(
        k=k,
        v=v,
        beta=beta,
        g=g,
368
369
370
371
372
373
374
375
376
377
378
379
380
        du=dv,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dk.add_(dk2)
    dg.add_(dg2)
    if dg.dtype != torch.float32:
        raise ValueError(f"dg current type is {dg.dtype} , should be float32")
    dg = chunk_local_cumsum(
        dg,
        chunk_size=chunk_size,
        reverse=True,
        cu_seqlens=cu_seqlens,
379
380
381
382
383
384
385
386
387
388
389
390
        reverse=True,
        cu_seqlens=cu_seqlens,
        head_first=False,
    )
    return dq, dk, dv, db, dg


def chunk_gated_delta_rule_bwd(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
412
413
414
415
416
417
418
419
420
        dht: Optional gradient of the terminal recurrent state.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
        chunk_size: Tokens per recurrence chunk.
    """
    w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare(
        q=q,
        k=k,
        v=v,
        g=g,
425
426
427
428
429
430
431
432
433
        do=do,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dh, dh0, dv = chunk_gated_delta_rule_bwd_state(
        q=q,
        k=k,
        w=w,
        g=g,
438
439
440
441
442
443
444
445
446
        scale=scale,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    dq, dk, dv, db, dg = chunk_gated_delta_rule_bwd_finish(
        q=q,
        k=k,
        v=v,
        g=g,
455
456
457
458
459
460
461
462
463
464
465
466
467
468
        scale=scale,
        cu_seqlens=cu_seqlens,
        chunk_size=chunk_size,
    )
    return dq, dk, dv, db, dg, dh0


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_fwd_prepare_saved(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
        use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    if scale is None:
        scale = k.shape[-1] ** -0.5

    q_norm, q_inv_norm = q, q.new_empty(0)
    k_norm, k_inv_norm = k, k.new_empty(0)
    if use_qk_l2norm_in_kernel:
        q_norm, q_inv_norm = _l2norm(q)
        k_norm, k_inv_norm = _l2norm(k)

    g_cumsum, matrix_a, w, u = chunk_gated_delta_rule_fwd_prepare(
        k=k_norm,
        v=v,
        g=g,
        beta=beta,
501
502
503
504
505
506
507
508
509
        beta=beta,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    return (
        q_norm,
        k_norm,
        q_inv_norm,
        k_inv_norm,
514
515
516
517
518
519
520
521
522
523
524
        scale,
    )


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_fwd_apply_state_saved(
        k_norm: torch.Tensor,
        g_cumsum: torch.Tensor,
        w: torch.Tensor,
        u: torch.Tensor,
538
539
540
541
542
543
544
545
546
        output_final_state: Whether to return the terminal state.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    return chunk_gated_delta_rule_fwd_apply_state(
        k=k_norm,
        g=g_cumsum,
        w=w,
        u=u,
550
551
552
553
554
555
556
557
558
559
560
        cu_seqlens=cu_seqlens,
    )


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_fwd_output_saved(
        q_norm: torch.Tensor,
        k_norm: torch.Tensor,
        g_cumsum: torch.Tensor,
        h: torch.Tensor,
574
575
576
577
578
579
580
581
582
        scale: Attention output scaling factor.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    return chunk_gated_delta_rule_fwd_output(
        q=q_norm,
        k=k_norm,
        v_new=v_new,
        h=h,
586
587
588
589
590
591
592
593
594
595
596
        cu_seqlens=cu_seqlens,
    )


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_fwd_saved(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
614
615
616
617
618
619
620
621
622
        use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    (
        q_norm,
        k_norm,
        q_inv_norm,
        k_inv_norm,
635
636
637
638
639
640
641
642
643
        use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    h, v_new, final_state = chunk_gated_delta_rule_fwd_apply_state_saved(
        k_norm,
        g_cumsum,
        w,
        u,
645
646
647
648
649
650
651
652
653
        output_final_state=True,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    output = chunk_gated_delta_rule_fwd_output_saved(
        q_norm,
        k_norm,
        g_cumsum,
        h,
655
656
657
658
659
660
661
662
663
        scale,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    return (
        output.to(q.dtype),
        final_state,
        q_norm,
        k_norm,
668
669
670
671
672
673
674
675
676
677
678
        scale,
    )


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_bwd_prepare_saved(
        q_norm: torch.Tensor,
        k_norm: torch.Tensor,
        v: torch.Tensor,
        g_cumsum: torch.Tensor,
698
699
700
701
702
703
704
705
706
        scale: Attention output scaling factor.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    return chunk_gated_delta_rule_bwd_prepare(
        q=q_norm,
        k=k_norm,
        v=v,
        g=g_cumsum,
713
714
715
716
717
718
719
720
721
722
723
        cu_seqlens=cu_seqlens,
    )


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_bwd_state_saved(
        q_norm: torch.Tensor,
        k_norm: torch.Tensor,
        g_cumsum: torch.Tensor,
        w: torch.Tensor,
743
744
745
746
747
748
749
750
751
        scale: Attention output scaling factor.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    return chunk_gated_delta_rule_bwd_state(
        q=q_norm,
        k=k_norm,
        w=w,
        g=g_cumsum,
758
759
760
761
762
763
764
765
766
767
768
        cu_seqlens=cu_seqlens,
    )


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_bwd_finish_saved(
        q: torch.Tensor,
        k: torch.Tensor,
        q_norm: torch.Tensor,
        k_norm: torch.Tensor,
806
807
808
809
810
811
812
813
814
        use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    dq, dk, dv, dbeta, dg = chunk_gated_delta_rule_bwd_finish(
        q=q_norm,
        k=k_norm,
        v=v,
        g=g_cumsum,
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
        scale=scale,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    if use_qk_l2norm_in_kernel:
        with torch.enable_grad():
            q_leaf = q.detach().requires_grad_(True)
            k_leaf = k.detach().requires_grad_(True)
            q_recomputed, _ = _l2norm(q_leaf)
            k_recomputed, _ = _l2norm(k_leaf)
            dq, dk = torch.autograd.grad(
                (q_recomputed, k_recomputed),
                (q_leaf, k_leaf),
                grad_outputs=(dq, dk),
            )
    del q_inv_norm, k_inv_norm
    return dq, dk, dv, dg, dbeta


@torch.compiler.disable
@input_guard
def chunk_gated_delta_rule_bwd_saved(
        q: torch.Tensor,
        k: torch.Tensor,
        q_norm: torch.Tensor,
        k_norm: torch.Tensor,
880
881
882
883
884
885
886
887
888
        use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization.
        chunk_size: Tokens per recurrence chunk.
        cu_seqlens: Optional cumulative offsets delimiting packed documents.
    """
    w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare_saved(
        q_norm,
        k_norm,
        v,
        g_cumsum,
893
894
895
896
897
898
899
900
901
        scale,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    dh, dh0, dv = chunk_gated_delta_rule_bwd_state_saved(
        q_norm,
        k_norm,
        g_cumsum,
        w,
906
907
908
909
910
911
912
913
914
        scale,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    dq, dk, dv, dg, dbeta = chunk_gated_delta_rule_bwd_finish_saved(
        q,
        k,
        q_norm,
        k_norm,
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
        use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
        chunk_size=chunk_size,
        cu_seqlens=cu_seqlens,
    )
    return dq, dk, dv, dg, dbeta, dh0


class ChunkGatedDeltaRuleFunction(torch.autograd.Function):
    """Autograd wrapper for the Triton-Ascend chunk Gated Delta Rule."""

    @staticmethod
    @input_guard
    @autocast_custom_fwd
    def forward(
            ctx: Any,
            q: torch.Tensor,
            k: torch.Tensor,
            v: torch.Tensor,
967
968
969
970
971
972
973
974
975
            cu_seqlens: Optional cumulative offsets delimiting packed documents.
            use_qk_l2norm_in_kernel: Whether local stages normalize Q/K and differentiate that normalization.
            chunk_size: Tokens per recurrence chunk.
        """
        g, output, matrix_a, final_state = chunk_gated_delta_rule_fwd(
            q=q,
            k=k,
            v=v,
            g=g,
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
            cu_seqlens=cu_seqlens,
            chunk_size=chunk_size,
        )

        saved_initial_state = initial_state if initial_state is not None else q.new_empty(0)
        saved_cu_seqlens = cu_seqlens if cu_seqlens is not None else q.new_empty(0, dtype=torch.long)
        ctx.save_for_backward(q, k, v, g, beta, matrix_a, saved_initial_state, saved_cu_seqlens)
        ctx.has_initial_state = initial_state is not None
        ctx.has_cu_seqlens = cu_seqlens is not None
        ctx.scale = scale
        ctx.chunk_size = chunk_size
        return output.to(q.dtype), final_state

    @staticmethod
    @input_guard
    @autocast_custom_bwd
    def backward(
            ctx: Any,
            do: torch.Tensor,
            dht: torch.Tensor
    ) -> tuple:
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
            ctx: Autograd context owned by this invocation.
            do: Gradient of the local output.
            dht: Optional gradient of the terminal recurrent state.
        """
        q, k, v, g, beta, matrix_a, initial_state, cu_seqlens = ctx.saved_tensors
        if not ctx.has_initial_state:
            initial_state = None
        if not ctx.has_cu_seqlens:
            cu_seqlens = None
        dq, dk, dv, db, dg, dh0 = chunk_gated_delta_rule_bwd(
            q=q,
            k=k,
            v=v,
            g=g,
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
            dht=dht,
            cu_seqlens=cu_seqlens,
            chunk_size=ctx.chunk_size,
        )
        return dq.to(q), dk.to(k), dv.to(v), dg.to(g), db.to(beta), None, dh0, None, None, None, None


@torch.compiler.disable
def chunk_gated_delta_rule(
        q: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        g: torch.Tensor,
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
            Outputs of shape `[B, T, H, V]`.
        final_state (Tensor):
            Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
    """
    if q.dtype != k.dtype or k.dtype != v.dtype:
        raise ValueError(
            f"q current type is {q.dtype}, k current type is {k.dtype}, "
            f"v current type is {v.dtype}, they should be equal"
        )
    if q.dtype == torch.float32:
        raise ValueError(
            "ChunkGatedDeltaRuleFunction does not support float32. Please use bfloat16."
        )
    if len(beta.shape) != 3:
        raise ValueError(
            f"beta current shape len is {len(beta.shape)}, beta must be of shape [B, T, H] if head_first=False, or [B, H, T] otherwise."
        )

    if head_first:
        warnings.warn(
            "head_first is deprecated and will be removed in a future version. "
            "Please use head_first=False for now instead."
        )
    if not head_first and q.shape[1] < q.shape[2]:
        warnings.warn(
            f"Input tensor shape suggests potential format mismatch: seq_len ({q.shape[1]}) < num_heads ({q.shape[2]}). "
            "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
            "when head_first=False was specified. "
            "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
            "This may indicate the inputs were passed in head-first format [B, H, T, ...] "
            "when head_first=False was specified. "
            "Please verify your input tensor format matches the expected shape [B, T, H, ...]."
        )
    if cu_seqlens is not None:
        if q.shape[0] != 1:
            raise ValueError(
                f"The batch size is expected to be 1 rather than {q.shape[0]} when using `cu_seqlens`."
                f"Please flatten variable-length inputs before processing."
            )
        if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
            raise ValueError(
                f"The number of initial states is expected to be equal to the number of input sequences, "
                f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
            )
    if scale is None:
        scale = k.shape[-1] ** -0.5

    if use_qk_l2norm_in_kernel:
        q, _ = _l2norm(q)
        k, _ = _l2norm(k)

    output, final_state = ChunkGatedDeltaRuleFunction.apply(
        q, k, v, g, beta, scale, initial_state, output_final_state, cu_seqlens, False, chunk_size,
    )
    return output, final_state


def _validate_fixed_summary_shape(
    key_dim: int,
    value_dim: int,
    chunk_size: int,
) -> None:
    if key_dim != 128 or value_dim != 128 or chunk_size != 64:
        raise NotImplementedError(
            "Triton GDN state summary requires key_dim=value_dim=128 and "
            "chunk_size=64."
        )
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
            "chunk_size=64."
        )


@torch.compiler.disable
def chunk_gated_delta_rule_state_summary_fwd(
    key: torch.Tensor,
    w: torch.Tensor,
    u: torch.Tensor,
    g: torch.Tensor,
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186

    Returns:
        FP32 additive state S and transition M, or None when M is omitted.
    """
    if (key.ndim, w.ndim, u.ndim, g.ndim) != (4, 4, 4, 3):
        raise ValueError("GDN state summary expects key/w/u [B,T,H,D] and g [B,T,H].")
    batch, seq_len, heads, key_dim = key.shape
    value_dim = u.shape[-1]
    _validate_fixed_summary_shape(key_dim, value_dim, chunk_size)
    if block_size not in (64, 128):
        raise ValueError(f"GDN state-summary block_size must be 64 or 128, got {block_size}.")
    if seq_len <= 0:
        raise ValueError("State summary requires a nonempty sample fragment.")
    if w.shape != key.shape or u.shape[:3] != key.shape[:3] or g.shape != key.shape[:3]:
        raise ValueError(
            "Incompatible GDN state-summary shapes: "
            f"key={tuple(key.shape)}, w={tuple(w.shape)}, "
            f"u={tuple(u.shape)}, g={tuple(g.shape)}."
        )
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
            f"key={tuple(key.shape)}, w={tuple(w.shape)}, "
            f"u={tuple(u.shape)}, g={tuple(g.shape)}."
        )

    key, w, u, g = (tensor.contiguous() for tensor in (key, w, u, g))
    packed_summary = torch.empty(
        batch,
        heads,
        key_dim,
        value_dim + key_dim,
1193
1194
1195
1196
1197
1198
1199
1200
1201
        value_dim + key_dim,
        device=key.device,
        dtype=torch.float32,
    )
    gdn_packed_state_summary_kernel[
        (triton.cdiv(value_dim + key_dim, block_size), batch * heads)
    ](
        key,
        w,
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
        BT=chunk_size,
        BV=block_size,
        NT=triton.cdiv(seq_len, chunk_size),
    )
    state_ext = packed_summary[..., :value_dim].contiguous()
    if not output_transition:
        return state_ext, None
    transition = packed_summary[..., value_dim:].contiguous()
    return state_ext, transition


def _validate_gdn_gradient_summary_inputs(
    query: torch.Tensor,
    key: torch.Tensor,
    w: torch.Tensor,
    g: torch.Tensor,
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
    dv: torch.Tensor,
    chunk_size: int,
) -> tuple[int, int, int, int, int]:
    """Validate the reverse summary inputs before launching its kernel."""
    batch, seq_len, heads, key_dim = query.shape
    value_dim = grad_output.shape[-1]
    _validate_fixed_summary_shape(key_dim, value_dim, chunk_size)
    if seq_len <= 0:
        raise ValueError("State summary requires a nonempty sample fragment.")
    qk_shape = (batch, seq_len, heads, key_dim)
    value_shape = (batch, seq_len, heads, value_dim)
    if (key.shape, w.shape, g.shape, grad_output.shape, dv.shape) != (
        qk_shape, qk_shape, qk_shape[:3], value_shape, value_shape
    ):
        raise ValueError(
            "Incompatible GDN state-gradient summary shapes: "
            f"query={tuple(query.shape)}, key={tuple(key.shape)}, "
            f"w={tuple(w.shape)}, g={tuple(g.shape)}, "
            f"grad_output={tuple(grad_output.shape)}, dv={tuple(dv.shape)}."
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
            f"query={tuple(query.shape)}, key={tuple(key.shape)}, "
            f"w={tuple(w.shape)}, g={tuple(g.shape)}, "
            f"grad_output={tuple(grad_output.shape)}, dv={tuple(dv.shape)}."
        )
    return batch, seq_len, heads, key_dim, value_dim


@torch.compiler.disable
def chunk_gated_delta_rule_state_gradient_summary_bwd(
    query: torch.Tensor,
    key: torch.Tensor,
    w: torch.Tensor,
    g: torch.Tensor,
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287

    Returns:
        FP32 incoming-state gradient with zero outgoing-state gradient.
    """
    batch, seq_len, heads, key_dim, value_dim = _validate_gdn_gradient_summary_inputs(
        query, key, w, g, grad_output, dv, chunk_size
    )

    query, key, w, g, grad_output, dv = (
        tensor.contiguous() for tensor in (query, key, w, g, grad_output, dv)
    )
    grad_state_ext = torch.empty(
        batch,
        heads,
        key_dim,
        value_dim,
1287
1288
1289
1290
1291
1292
1293
1294
1295
        value_dim,
        device=query.device,
        dtype=torch.float32,
    )
    gdn_state_grad_ext_kernel[(1, batch * heads)](
        query,
        key,
        w,
        g,
1304
1305
1306
1307
1308
        BT=chunk_size,
        BV=128,
        NT=triton.cdiv(seq_len, chunk_size),
    )
    return grad_state_ext
hyper_parallel/components/functional/kimi_delta_attention.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    beta: torch.Tensor,
) -> tuple[int, int, int, int, int, int]:
    """Validate dense token-first KDA inputs and return their dimensions."""
    if (query.dim(), key.dim(), value.dim(), gate.dim()) != (4, 4, 4, 4):
        raise ValueError("query, key, value, and gate must be rank-4 tensors.")
    if beta.dim() != 3:
        raise ValueError("beta must be a rank-3 tensor.")
    if query.shape != key.shape:
        raise ValueError("query and key must have identical shapes.")

    batch_size, sequence_length, num_k_heads, k_head_dim = query.shape
    value_batch, value_sequence, num_v_heads, v_head_dim = value.shape
    if (value_batch, value_sequence) != (batch_size, sequence_length):
        raise ValueError("value batch and sequence dimensions must match query.")
    if gate.shape != (batch_size, sequence_length, num_v_heads, k_head_dim):
        raise ValueError(
            "gate must have shape [B, S, num_v_heads, k_head_dim], got "
            f"{tuple(gate.shape)}."
        )
    if beta.shape != (batch_size, sequence_length, num_v_heads):
        raise ValueError(
            "beta must have shape [B, S, num_v_heads], got "
            f"{tuple(beta.shape)}."
        )
    if num_v_heads % num_k_heads != 0:
73
74
75
76
77
78
79
80
81
    name: str,
) -> torch.Tensor:
    """Return a gate parameter as ``[num_v_heads, k_head_dim]``."""
    if parameter.numel() != num_v_heads * k_head_dim:
        raise ValueError(
            f"{name} must contain {num_v_heads * k_head_dim} elements, "
            f"got {parameter.numel()}."
        )
    return parameter.reshape(num_v_heads, k_head_dim)
100
101
102
103
104
105
106
107
108
109
110
111
        dt_bias: Per-key time-step bias.
        lower_bound: Negative lower bound of the safe decay gate.
    """
    if gate_logits.dim() != 4:
        raise ValueError("gate_logits must have shape [B, S, H, K].")
    num_v_heads, k_head_dim = gate_logits.shape[-2:]
    if a_log.numel() != num_v_heads:
        raise ValueError(
            f"a_log must contain {num_v_heads} elements, got {a_log.numel()}."
        )
    bias = _reshape_gate_bias(dt_bias, num_v_heads, k_head_dim, "dt_bias")
    scale = a_log.float().exp().reshape(1, 1, num_v_heads, 1)
112
113
114
115
116
117
118
119
120
121
122
    preactivation = gate_logits.float() + bias.float().reshape(
        1, 1, num_v_heads, k_head_dim
    )
    if lower_bound is None:
        return -scale * F.softplus(preactivation)  # pylint: disable=not-callable
    if lower_bound >= 0:
        raise ValueError(f"lower_bound must be negative, got {lower_bound}.")
    return float(lower_bound) * torch.sigmoid(scale * preactivation)


def _prepare_kda_inputs(
146
147
148
149
150
151
152
153
154
            (key.float() * key.float()).sum(dim=-1, keepdim=True) + 1e-6
        ).to(key.dtype)
    if use_gate_in_kernel:
        if a_log is None or dt_bias is None:
            raise ValueError("a_log and dt_bias are required when gate activation is enabled.")
        gate = torch_kda_gate(
            gate,
            a_log,
            dt_bias,
176
177
178
179
180
181
182
183
184
    expected_shape = (value.shape[0], value.shape[2], k_head_dim, value.shape[3])
    if initial_state is None:
        return value.new_zeros(expected_shape, dtype=torch.float32)
    if tuple(initial_state.shape) != expected_shape:
        raise ValueError(
            f"initial_state must have shape {expected_shape}, got "
            f"{tuple(initial_state.shape)}."
        )
    return initial_state.float()
408
409
410
411
412
413
414
415
416
            use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, use_gate_in_kernel=use_gate_in_kernel,
            use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel, lower_bound=lower_bound, chunk_size=chunk_size,
        )
    if chunk_size <= 0:
        raise ValueError(f"chunk_size must be positive, got {chunk_size}.")
    output_dtype = value.dtype
    sequence_length = query.shape[1]
    query, key, value, gate, beta, scale = _prepare_kda_inputs(
        query,
545
546
547
548
549
550
551
552
553
        lower_bound: Negative lower bound of the safe decay gate.
        chunk_size: Number of tokens in a recurrence chunk.
    """
    if chunk_size <= 0:
        raise ValueError(f"chunk_size must be positive, got {chunk_size}.")
    _, key, value, gate, beta, _ = _prepare_kda_inputs(
        query, key, value, gate, beta,
        a_log=a_log,
        dt_bias=dt_bias,
620
621
622
623
624
625
626
627
628
        transition: Linear state transition matrix.
        initial_state: Optional state entering the first local chunk.
    """
    if initial_state is None:
        return state_ext.float()
    return (transition @ initial_state.to(transition) + state_ext).float()


def torch_compose_kda_state_summaries(
658
659
660
661
662
663
664
665
666
667
668
669
670

    Returns:
        The outgoing FP32 state.
    """
    if initial_state is None:
        return state_ext
    # Model autocast must not silently quantize a communicated FP32 state.
    with torch.autocast(device_type=state_ext.device.type, enabled=False):
        return torch.matmul(transition.float(), initial_state.float()) + state_ext


def apply_kda_state_gradient_summary(
    grad_state_ext: torch.Tensor,
677
678
679
680
681
682
683
684
685
686
687
        grad_state_ext: Local gradient contribution G.
        transition: Forward transfer M used by this backend's existing adjoint.
        grad_final_state: Incoming terminal-state gradient, or None for zero exit.
    """
    if grad_final_state is None:
        return grad_state_ext
    with torch.autocast(device_type=grad_state_ext.device.type, enabled=False):
        return (
            torch.matmul(transition.float().transpose(-2, -1), grad_final_state.float())
            + grad_state_ext
        )
701
702
703
704
705
706
707
708
709
710
711
    dt_bias: torch.Tensor,
    chunk_size: int,
) -> bool:
    """Check the fixed dense shapes accepted by the Triton KDA path."""
    batch_size, sequence_length, num_query_heads, key_dim = query.shape
    num_value_heads, value_dim = value.shape[2:]
    return all((
        value.shape[:2] == (batch_size, sequence_length),
        gate.shape == (batch_size, sequence_length, num_value_heads, key_dim),
        beta.shape == (batch_size, sequence_length, num_value_heads),
        num_value_heads % num_query_heads == 0,
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
    chunk_size: int,
    lower_bound: Optional[float],
) -> bool:
    """Check the fixed Kimi K3 contract validated by the fused backend."""
    operands = (key, value, gate, beta, a_log, dt_bias)
    if any(tensor is None for tensor in operands):
        return False
    if lower_bound is None:
        return False

    basic_contract = (
        query.device.type == "npu",
        all(tensor.dtype == torch.bfloat16 for tensor in (query, key, value, gate, beta)),
        all(tensor.dtype == torch.float32 for tensor in (a_log, dt_bias)),
        all(tensor.ndim == 4 for tensor in (query, key, value, gate)),
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
        all(tensor.ndim == 4 for tensor in (query, key, value, gate)),
        beta.ndim == 3,
        query.shape == key.shape,
    )
    if not all(basic_contract):
        return False

    shape_supported = _has_triton_kda_shapes(
        query, value, gate, beta, a_log, dt_bias, chunk_size,
    )
    lower_bound_supported = -5.0 <= lower_bound < 0
    if not (shape_supported and lower_bound_supported):
        return False
    return all(tensor.device == query.device for tensor in operands)


def is_triton_kda_available(
    query: Optional[torch.Tensor] = None,
779
780
781
782
783
784
785
786
787
788
789
        dt_bias: Per-key time-step bias.
        chunk_size: Number of tokens in a recurrence chunk.
        lower_bound: Negative lower bound of the safe decay gate.
    """
    if chunk_size != _TRITON_KDA_CHUNK_SIZE:
        return False
    if query is not None and not _is_triton_kda_input_supported(
        query,
        key,
        value,
        gate,
792
793
794
795
796
797
798
799
800
801
        dt_bias,
        chunk_size=chunk_size,
        lower_bound=lower_bound,
    ):
        return False
    return is_fla_triton_kda_available()


def _normalize_kda_backend(backend: str) -> str:
    """Normalize the selected backend and reject unsupported names."""
800
801
802
803
804
805
806
807
808
def _normalize_kda_backend(backend: str) -> str:
    """Normalize the selected backend and reject unsupported names."""
    backend = backend.lower()
    if backend not in _KDA_BACKENDS:
        raise ValueError(
            f"unsupported KDA backend {backend!r}; "
            f"expected one of {sorted(_KDA_BACKENDS)}."
        )
    return backend
809
810
811
812
813
814
815
816
817
818
819
820
821
822


def _validate_fused_state_contract(initial_state, output_final_state, qk_norm, gate, beta, backend) -> None:
    """Keep raw-input dispatch separate from the stateful CP backend contract."""
    if initial_state is not None or output_final_state:
        raise NotImplementedError(
            f"KDA backend={backend!r} currently supports zero initial state without "
            "returning a final state; stateful execution is owned by the CP backend."
        )
    if not (qk_norm and gate and beta):
        raise NotImplementedError(
            f"KDA backend={backend!r} requires fused Q/K normalization, gate activation, "
            "and beta sigmoid."
        )
863
864
865
866
867
868
869
870
871
        backend: Explicit local operator implementation to dispatch.
        cu_seqlens: Cumulative document boundaries for packed tokens.
    """
    if query.ndim == 3:
        output, final = chunk_kda(
            *(tensor.unsqueeze(0) for tensor in (query, key, value, gate, beta)),
            a_log=a_log, dt_bias=dt_bias, scale=scale, initial_state=initial_state,
            output_final_state=output_final_state, use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
            use_gate_in_kernel=use_gate_in_kernel, use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
869
870
871
872
873
874
875
876
877
            a_log=a_log, dt_bias=dt_bias, scale=scale, initial_state=initial_state,
            output_final_state=output_final_state, use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
            use_gate_in_kernel=use_gate_in_kernel, use_beta_sigmoid_in_kernel=use_beta_sigmoid_in_kernel,
            lower_bound=lower_bound, chunk_size=chunk_size, backend=backend, cu_seqlens=cu_seqlens)
        return output.squeeze(0), final
    backend = _normalize_kda_backend(backend)
    if backend == "eager":
        return torch_chunk_kda(
            query, key, value, gate, beta,
886
887
888
889
890
891
892
893
894
895
896
897
            lower_bound=lower_bound,
            chunk_size=chunk_size,
            cu_seqlens=cu_seqlens,
        )
    _validate_fused_state_contract(initial_state, output_final_state, use_qk_l2norm_in_kernel,
                                  use_gate_in_kernel, use_beta_sigmoid_in_kernel, backend)
    if backend == "ascendc":
        output = ascendc_chunk_kda(
            query, key, value, gate, beta,
            a_log=a_log.float() if a_log is not None else None,
            dt_bias=dt_bias.float() if dt_bias is not None else None,
            scale=scale, lower_bound=lower_bound, chunk_size=chunk_size, cu_seqlens=cu_seqlens,
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
            a_log=a_log.float() if a_log is not None else None,
            dt_bias=dt_bias.float() if dt_bias is not None else None,
            scale=scale, lower_bound=lower_bound, chunk_size=chunk_size, cu_seqlens=cu_seqlens,
        )
        return output, None
    triton_a_log = a_log.float() if a_log is not None else None
    triton_dt_bias = dt_bias.float() if dt_bias is not None else None
    if not _is_triton_kda_input_supported(
        query, key, value, gate, beta, triton_a_log, triton_dt_bias,
        chunk_size=chunk_size,
        lower_bound=lower_bound,
    ):
        raise RuntimeError(
            "KDA backend='triton' received an unsupported input contract; it requires "
            "q/k/v/gate/beta=bf16, a_log/dt_bias=fp32, "
            "head_k_dim=head_v_dim=128, chunk_size=64, and a supported safe gate."
        )
910
911
912
913
914
915
916
917
918
            "head_k_dim=head_v_dim=128, chunk_size=64, and a supported safe gate."
        )


    output = fused_chunk_kda(
        query, key, value, gate, beta,
        a_log=triton_a_log,
        dt_bias=triton_dt_bias,
        scale=scale,
920
921
922
923
924
        chunk_size=chunk_size,
        safe_gate=True,
        cu_seqlens=cu_seqlens,
    )
    return output, None
hyper_parallel/components/functional/kimi_delta_attention_ascendc.py
88
89
90
91
92
93
94
95
96

    Returns:
        Native save-mode tensors in the public Prepare ABI order.
    """
    ops = load_kda_native_ops()
    query, key, value, gate, beta, a_log, dt_bias = inputs
    result = ops.chunk_kda_fwd_prepare(
        query, key, value, gate.transpose(1, 2).contiguous(), beta.transpose(1, 2).contiguous(),
        scale, layout="BNSD", chunk_size=64,
100
101
102
103
104
105
106
107
108
        use_exp2=True, backward_mode="save", **metadata,
    )
    if len(result) != 13 or any(not isinstance(tensor, torch.Tensor) for tensor in result):
        raise RuntimeError("fla-npu Prepare must return all 13 tensors for native-norm save mode.")
    return KDANativePrepared(*result)


def _native_backward_view(tensor: torch.Tensor, packed: bool) -> torch.Tensor:
    """Expose packed NTD views without copying the B=1 Prepare/FwdH storage."""
147
148
149
150
151
152
153
154
155
    if query.ndim != 4:
        raise ValueError("KDA inputs must have shape [B,T,H,K] or packed [T,H,K].")
    if chunk_size != 64:
        raise ValueError("Ascend C KDA uses chunk_size=64.")
    metadata = local_chunk_metadata(cu_seqlens, query.shape[1])
    if metadata and query.shape[0] != 1:
        raise ValueError("Packed Ascend C KDA requires B=1.")
    scale = query.shape[-1] ** -0.5 if scale is None else float(scale)
    tokens = tuple(tensor.transpose(1, 2).contiguous() for tensor in (query, key, value))
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
        scale: Attention output scale.
        lower_bound: Safe gate lower bound retained for backward.
        metadata: Local packed indices, or an empty dense descriptor.
    """
    ops = load_kda_native_ops()
    _, _, value, gate, _, a_log, dt_bias = inputs
    hidden, v_new, _ = ops.chunk_fwd_h(
        prepared.kg, prepared.w, prepared.u, gk=prepared.gk, initial_state=initial,
        output_final_state=False, use_exp2=True, **metadata)
    output = ops.chunk_kda_fwd_finalize(
        prepared.qg_scaled, prepared.aqk, v_new, hidden, output_layout="BSND", **metadata)
    prepared = prepared._replace(u=None, qg_scaled=None)
    # Entry states are retained for the native local backward.
    ctx.save_for_backward(value, gate, a_log, dt_bias, *prepared, hidden, v_new)
    ctx.dtypes = tuple(tensor.dtype for tensor in inputs)
    ctx.scale, ctx.lower_bound, ctx.native_metadata = scale, lower_bound, metadata
    return output


def prepare_kda_native_backward(ctx: Any, saved_tensors: tuple, grad_output: torch.Tensor) -> tuple:
    """Prepare local gradients independently of the terminal state gradient.
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

    Returns:
        Head-major dO and the native dAqk, local dV and raw dQ intermediates.
    """
    ops = load_kda_native_ops()
    prepared = KDANativePrepared(*saved_tensors[4:-2])
    hidden, v_new = saved_tensors[-2:]
    packed = bool(ctx.native_metadata)

    grad = grad_output.transpose(1, 2).contiguous()
    d_aqk, dv_local, dq_raw = ops.chunk_kda_bwd_prepare(
        *(_native_backward_view(tensor, packed) for tensor in (prepared.aqk, v_new, grad, hidden)), scale=ctx.scale,
        layout="NTD" if packed else "BNSD", chunk_size=64, **ctx.native_metadata)
    dv_local_head = dv_local.unsqueeze(0) if packed else dv_local
    return grad, d_aqk, dv_local_head, dq_raw


def finish_kda_native_backward(ctx: Any, saved_tensors: tuple, grad: torch.Tensor, d_aqk: torch.Tensor,
                               dv_local_head: torch.Tensor, dq_raw: torch.Tensor,
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

    Returns:
        Seven input gradients, cast to their original dtypes.
    """
    ops = load_kda_native_ops()
    value, gate, a_log, dt_bias, *saved = saved_tensors
    (gk, _, akk, weights, _, qg, kg, _, query, key,
     query_rstd, key_rstd, beta, hidden, v_new) = saved
    packed = bool(ctx.native_metadata)

    hidden_grad, _, dv_scan = ops.chunk_gated_delta_rule_bwd_dhu(
        qg, kg, weights, grad, dv_local_head, ctx.scale, 64,
        gK=gk, h0=None, dht=terminal, use_exp2=True, **ctx.native_metadata)
    dq, dk, dv, dbeta, dgate, da_log, ddt_bias = ops.chunk_kda_bwd_finalize(
        *(_native_backward_view(tensor, packed)
          for tensor in (query, key, value, gk, gate.transpose(1, 2).contiguous(), beta)),
        a_log, dt_bias,
        *(_native_backward_view(tensor, packed) for tensor in (akk, v_new, hidden, hidden_grad, dv_scan)),
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        q_rstd=_native_backward_view(query_rstd, packed),
        k_rstd=_native_backward_view(key_rstd, packed),
        use_beta_sigmoid_in_kernel=False,
        output_layout="NTD" if packed else "BNSD", **ctx.native_metadata)
    if packed:
        dq, dk, dv, dbeta, dgate = (tensor.unsqueeze(0) for tensor in (dq, dk, dv, dbeta, dgate))
    # Prepare already saves FP32 sigmoid(beta); reuse it without device-specific
    # native epilogue selection, recomputing sigmoid, or retaining raw beta.
    dbeta = torch.ops.aten.sigmoid_backward.default(dbeta, beta)
    dbeta, dgate = dbeta.transpose(1, 2), dgate.transpose(1, 2)
    gradients = (dq, dk, dv, dgate, dbeta, da_log, ddt_bias.reshape_as(dt_bias))
    return tuple(gradient.to(dtype) for gradient, dtype in zip(gradients, ctx.dtypes))


class _AscendCKDAStages(torch.autograd.Function):
    """Native local KDA autograd, without communication resources or protocol callbacks."""
283
284
285
286
287
288
289
290
291
292
            lower_bound: Lower bound of the safe decay gate.
            metadata: Native packed-document offsets and chunk indices.
        """
        inputs = (query, key, value, gate, beta, a_log, dt_bias)
        prepared = prepare_kda_native(inputs, scale, lower_bound, metadata)
        return finish_kda_native_forward(ctx, inputs, prepared, None, scale, lower_bound, metadata)

    @staticmethod
    @once_differentiable
    def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
296
297
298
299
300
301
302
303
            ctx: Autograd context owned by this invocation.
            grad_output: Gradient of the local output.
        """
        # Unpack once: non-reentrant checkpoint hooks consume saved tensors.
        saved = ctx.saved_tensors
        prepared = prepare_kda_native_backward(ctx, saved, grad_output)
        gradients = finish_kda_native_backward(ctx, saved, *prepared, None)
        return (*gradients, None, None, None)
hyper_parallel/components/functional/kimi_delta_attention_triton.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89


def _get_attribute(module_name: str, attribute: str) -> Any:
    """Import one required FLA symbol with a useful compatibility error."""
    try:
        module = importlib.import_module(module_name)
    except ModuleNotFoundError as exc:
        missing_name = getattr(exc, "name", None)
        is_fla_module = (
            missing_name is not None and str(missing_name).startswith("fla.")
        )
        if missing_name == module_name or is_fla_module:
            raise RuntimeError(
                "The installed FLA package is incompatible with Hyper KDA: "
                f"missing module {module_name}."
            ) from exc
        raise RuntimeError(
            f"FLA module {module_name} could not load runtime dependency "
            f"{missing_name!r}."
        ) from exc
    except ImportError as exc:
        raise RuntimeError(
            f"FLA module {module_name} failed to import; inspect the chained "
            "exception for the incompatible runtime library."
        ) from exc
    try:
        return getattr(module, attribute)
    except AttributeError as exc:
        raise RuntimeError(
            "The installed FLA package is incompatible with Hyper KDA: "
            f"missing {module_name}.{attribute}. Install an FLA revision with "
            "the Triton-Ascend KDA backend."
        ) from exc
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113


def _parse_version(version: str) -> tuple[int, int, int]:
    """Parse the numeric prefix of an FLA semantic version."""
    match = re.match(r"^(\d+)\.(\d+)\.(\d+)", version)
    if match is None:
        raise RuntimeError(f"Unable to parse the installed FLA version {version!r}.")
    return tuple(int(part) for part in match.groups())


def _require_triton_ascend() -> None:
    """Require the external FLA runtime to have a Triton Ascend backend."""
    try:
        importlib.import_module("triton")
        ascend_backend = importlib.util.find_spec("triton.backends.ascend")
    except (ImportError, ModuleNotFoundError) as exc:
        raise RuntimeError(
            "KDA backend='triton' requires Triton-Ascend in the runtime environment."
        ) from exc
    if ascend_backend is None:
        raise RuntimeError(
            "KDA backend='triton' found Triton, but its Ascend backend is missing."
        )

113
114
115
116
117
118
119
120
121


def _require_npu_backends() -> None:
    """Verify that FLA registered every backend used by the staged P2P path."""
    backend_specs = (
        (
            "fla.ops.kda.backends.triton_ascend",
            "TritonAscendKDABackend",
        ),
127
128
129
130
131
132
133
134
135
136
137
            "fla.ops.gla.backends.triton_ascend",
            "TritonAscendGLABackend",
        ),
    )
    for module_name, class_name in backend_specs:
        backend = _get_attribute(module_name, class_name)
        if not backend.is_available():
            raise RuntimeError(
                "KDA backend='triton' requires FLA's Triton-Ascend backend "
                f"{class_name}, but it is unavailable in this process."
            )
144
145
146
147
148
149
150
151
152
        fla = importlib.import_module("fla")
    except ModuleNotFoundError as exc:
        missing_name = getattr(exc, "name", None)
        if missing_name != "fla":
            raise RuntimeError(
                "The external FLA package is present but cannot load runtime "
                f"dependency {missing_name!r}."
            ) from exc
        raise RuntimeError(
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
        raise RuntimeError(
            "KDA backend='triton' requires the optional flash-linear-attention "
            "package with its Triton-Ascend KDA backend."
        ) from exc
    except ImportError as exc:
        raise RuntimeError(
            "The external FLA package is present but failed to import; inspect "
            "the chained exception for the incompatible runtime library."
        ) from exc

    version = getattr(fla, "__version__", None)
    if not isinstance(version, str):
        raise RuntimeError("The installed FLA package does not expose __version__.")
    if _parse_version(version) < _MIN_FLA_VERSION:
        minimum = ".".join(str(part) for part in _MIN_FLA_VERSION)
        raise RuntimeError(
            f"KDA backend='triton' requires FLA >= {minimum}, got {version}."
        )

    _require_triton_ascend()
    backend = _get_attribute("fla.ops.kda.backends.triton_ascend", "TritonAscendKDABackend")
    if not backend.is_available():
        raise RuntimeError("FLA Triton-Ascend KDA backend is unavailable in this process.")
    return _FLAKDARuntime(version=version, chunk_kda=_get_attribute("fla.ops.kda", "chunk_kda"))


def is_fla_triton_kda_available() -> bool:
    """Return whether the optional external FLA KDA backend is usable."""
    try:
        _require_fla_kda_runtime()
    except RuntimeError:
        return False
    return True


@lru_cache(maxsize=1)
def get_fla_kda_staged_ops() -> FLAKDAStagedOps:
187
188
189
190
191
192
193
194
195
196
@lru_cache(maxsize=1)
def get_fla_kda_staged_ops() -> FLAKDAStagedOps:
    """Return FLA staged operators for Hyper's state-P2P autograd function."""
    _require_fla_kda_runtime()
    _require_npu_backends()
    return FLAKDAStagedOps(
        l2norm_fwd=_get_attribute("fla.modules.l2norm", "l2norm_fwd"),
        l2norm_bwd=_get_attribute("fla.modules.l2norm", "l2norm_bwd"),
        fused_beta_sigmoid=_get_attribute(
            "fla.ops.common.gate", "fused_beta_sigmoid"
269
270
271
272
273
274
275
276
277
278

    Returns:
        Attention output and the optional outgoing state.
    """
    runtime = _require_fla_kda_runtime()
    return runtime.chunk_kda(
        q=query,
        k=key,
        v=value,
        g=gate,
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    gate: torch.Tensor,
    beta: torch.Tensor,
) -> tuple[int, int, int, int]:
    """Validate local KDA tensor shapes and return dimensions used by later checks."""
    if (query.ndim, key.ndim, value.ndim, gate.ndim) != (4, 4, 4, 4):
        raise ValueError("Fused KDA expects rank-4 query/key/value/gate tensors.")
    if beta.ndim != 3:
        raise ValueError("Fused KDA expects a rank-3 beta tensor.")
    if query.shape != key.shape:
        raise ValueError("Fused KDA query and key must have identical shapes.")
    batch, sequence_length, num_query_heads, key_dim = query.shape
    num_value_heads, value_dim = value.shape[2:]
    if value.shape[:2] != (batch, sequence_length):
        raise ValueError("Fused KDA value must match query batch and sequence dimensions.")
    if gate.shape != (batch, sequence_length, num_value_heads, key_dim):
        raise ValueError("Fused KDA gate has an incompatible shape.")
    if beta.shape != (batch, sequence_length, num_value_heads):
        raise ValueError("Fused KDA beta has an incompatible shape.")
    if num_value_heads % num_query_heads:
        raise ValueError("Fused KDA value heads must be divisible by query heads.")
    return sequence_length, key_dim, value_dim, num_value_heads


def validate_triton_kda_inputs(
    query: torch.Tensor,
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        dt_bias: FP32 per-channel gate bias.
        chunk_size: Kernel chunk size, currently 64.
        lower_bound: Safe gate lower bound in [-5,0).
    """
    _, key_dim, value_dim, num_value_heads = _validate_local_shapes(
        query, key, value, gate, beta
    )
    if not (
        query.dtype == key.dtype == value.dtype == gate.dtype == beta.dtype
        == torch.bfloat16
    ):
        raise TypeError("Fused KDA requires q/k/v/gate/beta tensors in bfloat16.")
    if a_log.dtype != torch.float32 or dt_bias.dtype != torch.float32:
        raise TypeError("Fused KDA requires a_log and dt_bias tensors in float32.")
    if key_dim != 128 or value_dim != 128 or chunk_size != 64:
        raise NotImplementedError(
            "Fused KDA currently requires key_dim=value_dim=128 and chunk_size=64."
        )
    if a_log.numel() != num_value_heads:
        raise ValueError("Fused KDA a_log must contain one value per value head.")
    if dt_bias.numel() != num_value_heads * key_dim:
        raise ValueError("Fused KDA dt_bias must contain one value per gate channel.")
    if not -5.0 <= lower_bound < 0:
        raise ValueError("Fused KDA lower_bound must lie in [-5, 0).")
    if not query.is_npu:
        raise RuntimeError("The fused KDA backend requires Ascend NPU tensors.")
    if any(
        tensor.device != query.device
        for tensor in (key, value, gate, beta, a_log, dt_bias)
    ):
        raise ValueError("Fused KDA inputs must reside on the same NPU device.")
    _require_fla_kda_runtime()


def fused_chunk_kda(
    query: torch.Tensor,
403
404
405
406
407
408
409
410
411
        lower_bound: Lower bound for the activated gate.
        chunk_size: Tokens per local recurrence chunk.
        safe_gate: Use the staged lower-bounded gate implementation.
    """
    validate_triton_kda_inputs(
        query,
        key,
        value,
        gate,
414
415
416
417
418
419
420
421
422
        dt_bias,
        chunk_size=chunk_size,
        lower_bound=lower_bound,
    )
    output, _ = run_fla_chunk_kda(
        query,
        key,
        value,
        gate,
428
429
430
431
432
433
434
435
436
        chunk_size=chunk_size,
        safe_gate=safe_gate,
        cu_seqlens=cu_seqlens,
    )
    return output


def validate_kda_state_summary(state: torch.Tensor, matrix: torch.Tensor) -> None:
    """Validate the fixed KDA affine contract before communication.
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    gate: torch.Tensor,
    chunk_size: int,
) -> tuple[int, int, int, int, int]:
    """Validate the fixed Kimi K3 summary contract and return dimensions."""
    if (key.ndim, w.ndim, u.ndim, gate.ndim) != (4, 4, 4, 4):
        raise ValueError("KDA prepared summary expects rank-4 key/w/u/gate tensors.")
    batch, sequence_length, heads, key_dim = key.shape
    value_dim = u.shape[-1]
    if key_dim != 128 or value_dim != 128 or chunk_size != 64:
        raise NotImplementedError(
            "Triton KDA state summary requires key_dim=value_dim=128 and "
            "chunk_size=64."
        )
    if sequence_length <= 0:
        raise ValueError("State summary requires a nonempty sample fragment.")
    if w.shape != key.shape or gate.shape != key.shape:
        raise ValueError(
            "KDA prepared key, w, and gate must have identical shapes, got "
            f"key={tuple(key.shape)}, w={tuple(w.shape)}, gate={tuple(gate.shape)}."
        )
    if u.shape[:3] != key.shape[:3]:
        raise ValueError(
            f"KDA prepared u prefix {tuple(u.shape[:3])} must match "
            f"key prefix {tuple(key.shape[:3])}."
        )
    if not key.is_npu:
        raise RuntimeError("Triton KDA state summary requires Ascend NPU tensors.")
    return batch, sequence_length, heads, key_dim, value_dim


def _validate_gradient_summary_inputs(
    query: torch.Tensor,
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
    grad_value: torch.Tensor,
    chunk_size: int,
) -> tuple[int, int, int, int, int]:
    """Validate prepared tensors used by the reverse state wavefront."""
    tensors = (query, key, w, gate, grad_output, grad_value)
    if any(tensor.ndim != 4 for tensor in tensors):
        raise ValueError(
            "KDA gradient summary expects rank-4 query/key/w/gate/do/dv tensors."
        )
    batch, sequence_length, heads, key_dim = query.shape
    value_dim = grad_output.shape[-1]
    if key_dim != 128 or value_dim != 128 or chunk_size != 64:
        raise NotImplementedError(
            "Triton KDA state-gradient summary requires key_dim=value_dim=128 "
            "and chunk_size=64."
        )
    if sequence_length <= 0:
        raise ValueError("State summary requires a nonempty sample fragment.")
    prepared_shape = (batch, sequence_length, heads, key_dim)
    value_shape = (batch, sequence_length, heads, value_dim)
    if key.shape != prepared_shape or w.shape != prepared_shape:
        raise ValueError(
            "KDA prepared query, key, and w must have identical shapes, got "
            f"query={tuple(query.shape)}, key={tuple(key.shape)}, "
            f"w={tuple(w.shape)}."
        )
    if gate.shape != prepared_shape:
        raise ValueError(
            f"KDA prepared gate shape {tuple(gate.shape)} must match "
            f"query shape {prepared_shape}."
        )
    if grad_output.shape != value_shape or grad_value.shape != value_shape:
        raise ValueError(
            "KDA grad_output and grad_value must have shape "
            f"{value_shape}, got do={tuple(grad_output.shape)}, "
            f"dv={tuple(grad_value.shape)}."
        )
    if not query.is_npu:
        raise RuntimeError(
            "Triton KDA state-gradient summary requires Ascend NPU tensors."
        )
    return batch, sequence_length, heads, key_dim, value_dim


def _launch_kda_state_summary(
    key: torch.Tensor,
541
542
543
544
545
546
547
548
549
    chunk_size: int,
    output_transition: bool = True,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
    """Launch the shared S/M summary used by the state CP protocols."""
    return _launch_kda_paired_state_summary(
        key,
        w,
        u,
        gate,
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
    block_size: int = 64,
) -> torch.Tensor:
    """Launch the reverse-wavefront Triton-Ascend summary kernel."""
    # Triton is optional until a summary kernel is actually launched.
    import triton  # pylint: disable=import-outside-toplevel

    from ._triton.kimi_delta_attention.state_summary import (  # pylint: disable=import-outside-toplevel
        kda_state_grad_ext_kernel,
    )

    batch, sequence_length, heads, key_dim, value_dim = (
        _validate_gradient_summary_inputs(
            query,
            key,
            w,
582
583
584
585
586
587
588
589
590
591
592
593
594
            grad_value,
            chunk_size,
        )
    )
    query, key, w, gate, grad_output, grad_value = (
        tensor.contiguous()
        for tensor in (query, key, w, gate, grad_output, grad_value)
    )
    grad_state_ext = torch.empty(
        batch,
        heads,
        key_dim,
        value_dim,
594
595
596
597
598
599
600
601
602
        value_dim,
        dtype=torch.float32,
        device=query.device,
    )
    kda_state_grad_ext_kernel[
        (triton.cdiv(value_dim, block_size), batch * heads)
    ](
        query,
        key,
615
616
617
618
619
620
621
622
623
        BT=chunk_size,
        BV=block_size,
        num_warps=2,
    )
    return grad_state_ext


@torch.compiler.disable
def _launch_kda_paired_state_summary(
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
    output_transition: bool = True,
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
    """Build Ascend FLA-paired ``S_ext`` and an explicit FP32 transfer ``M``."""
    # Triton is optional until a summary kernel is actually launched.
    import triton  # pylint: disable=import-outside-toplevel

    from ._triton.kimi_delta_attention.state_summary import (  # pylint: disable=import-outside-toplevel
        kda_split_state_summary_kernel,
        kda_state_transition_kernel,
    )

    batch, sequence_length, heads, key_dim, value_dim = (
        _validate_prepared_summary_inputs(key, w, u, gate, chunk_size)
    )
    key, w, u, gate = (
        tensor.contiguous() for tensor in (key, w, u, gate)
    )
    state_ext = torch.empty(
        batch,
        heads,
        key_dim,
        value_dim,
651
652
653
654
655
656
657
658
659
660
661
        value_dim,
        dtype=torch.float32,
        device=key.device,
    )
    transition = None
    if output_transition:
        transition = torch.empty(
            batch,
            heads,
            key_dim,
            key_dim,
661
662
663
664
665
666
667
668
669
            key_dim,
            dtype=torch.float32,
            device=key.device,
        )
    kda_split_state_summary_kernel[(1, batch * heads)](
        key,
        w,
        u,
        gate,
679
680
681
682
683
684
685
686
687
688
        BV=128,
        OUTPUT_MODE=1,
        num_warps=2,
    )
    if output_transition:
        kda_state_transition_kernel[(triton.cdiv(key_dim, 64), batch * heads)](
            key,
            w,
            gate,
            transition,
693
694
695
696
697
698
699
700
701
            BV=64,
            num_warps=4,
            num_stages=2,
        )
    return state_ext, transition


@torch.compiler.disable
def kda_state_summary_forward_from_prepared(
724
725
726
727
728
729
730
731
732

    Returns:
        The FP32 state S and the FP32 transition M, or None when M is omitted.
    """
    return _launch_kda_state_summary(
        key,
        w,
        u,
        gate,
766
767
768
769
770
771
772
773
774

    Returns:
        FP32 local contribution G, shaped [B,H,K,V].
    """
    return _launch_kda_state_gradient_summary(
        query,
        key,
        w,
        gate,
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

    Returns:
        Contiguous FP32 recurrent state or state gradient shaped [B,H,128,128].
    """
    if states.ndim != 5 or states.shape != matrices.shape or states.shape[0] == 0:
        raise ValueError("KDA merge requires matching rank-stacked summaries.")
    size, batch, heads = states.shape[:3]
    validate_kda_state_summary(states[0], matrices[0])
    if not 0 <= rank < size:
        raise ValueError("KDA merge rank is outside the summary group.")
    if any(t.stride(1) != heads * t.stride(2) or t.stride(-1) != 1 for t in (states, matrices)):
        raise ValueError("KDA merge requires consecutive batch/head slabs and columns.")
    if states.device.type != "npu":
        raise ValueError("KDA fused state merge requires Ascend NPU tensors.")
    count = rank if forward else size - rank - 1
    output = states.new_empty((batch, heads, 128, 128))
    if count == 0:
        return output.zero_()
    # Triton is optional for imports; production merging requires Ascend.
    # pylint: disable=import-outside-toplevel
    from hyper_parallel.components.functional._triton.kimi_delta_attention.cp_merge import (
        kda_cached_affine_merge_kernel,
    )
    # pylint: enable=import-outside-toplevel

    kda_cached_affine_merge_kernel[(2, batch * heads)](
        output, states, matrices, count, rank,
        state_rank_stride=states.stride(0), state_head_stride=states.stride(2), state_row_stride=states.stride(3),
        matrix_rank_stride=matrices.stride(0), matrix_head_stride=matrices.stride(2),
        matrix_row_stride=matrices.stride(3),
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
        state_rank_stride=states.stride(0), state_head_stride=states.stride(2), state_row_stride=states.stride(3),
        matrix_rank_stride=matrices.stride(0), matrix_head_stride=matrices.stride(2),
        matrix_row_stride=matrices.stride(3),
        forward=forward, block_v=64, num_warps=2, num_stages=2)
    return output


def _validate_scan_range(indices: range, size: int, forward: bool, prefix_count: int | None) -> None:
    """Check the requested chronological interval and optional saved prefix."""
    count = len(indices)
    if prefix_count is not None and not 0 <= prefix_count <= count:
        raise ValueError("The saved prefix must lie within the scan interval.")
    if count:
        endpoints_valid = all(0 <= index < size for index in (indices[0], indices[-1]))
        if indices.step != (1 if forward else -1) or not endpoints_valid:
            raise ValueError("KDA scans require an ordered interval inside the group.")


def scan_kda_affine_maps(maps: torch.Tensor, incoming: torch.Tensor,
               indices: range, forward: bool, prefix_count: int | None = None,
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874

    Returns:
        The outgoing state and the optional saved intermediate prefix.
    """
    count = len(indices)
    _validate_scan_range(indices, maps.shape[0], forward, prefix_count)
    if not count:
        return incoming, incoming if prefix_count == 0 else None
    if incoming.device.type != "npu" or not incoming.is_contiguous():
        raise ValueError("KDA fused scans require a contiguous Ascend input state.")
    output = torch.empty_like(incoming)
    prefix = None
    if prefix_count is not None:
        prefix = incoming if prefix_count == 0 else output if prefix_count == count else torch.empty_like(incoming)
    save_prefix = prefix is not None and prefix_count not in (0, count)
    # Keep the optional Triton dependency out of CPU-only model imports.
    # pylint: disable=import-outside-toplevel
    from hyper_parallel.components.functional._triton.kimi_delta_attention.cp_merge import kda_affine_scan_kernel
    # pylint: enable=import-outside-toplevel

    batch, heads = incoming.shape[:2]
    kda_affine_scan_kernel[(2, batch * heads)](
        output, prefix, maps, incoming, count, indices.start, prefix_count or 0,
        rank_stride=maps.stride(0), head_stride=maps.stride(2), row_stride=maps.stride(3),
        forward=forward, save_prefix=save_prefix, block_v=64, num_warps=2, num_stages=2)
    return output, prefix
hyper_parallel/components/functional/linear_attention_convolution.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
        convolution: Source depthwise short convolution.
        require_activation: KDA source ShortConv declares its SiLU activation.
    """
    if convolution.stride != (1,):
        raise ValueError("Linear-attention ShortConv requires stride=1")
    if convolution.groups != convolution.in_channels or convolution.out_channels != convolution.in_channels:
        raise ValueError("Linear-attention ShortConv requires depthwise equal input/output channels")
    padding = (convolution.kernel_size[0] - 1) * convolution.dilation[0]
    if convolution.padding != (padding,) or convolution.padding_mode != "zeros":
        raise ValueError("Linear-attention ShortConv requires causal zero padding")
    if require_activation and getattr(convolution, "activation", None) not in ("silu", "swish"):
        raise ValueError("KDA ShortConv requires a declared SiLU/Swish activation")


def validate_conv_backend(backend: str) -> str:
    """Validate an explicit convolution backend without loading kernels.
134
135
136
137
138
139
140
141
142
143
144
145
    width: int,
) -> tuple[torch.Tensor, tuple[int, ...] | None, int]:
    """Prepend valid history while preserving dense samples and packed resets."""
    if info is None:
        if halo is None:
            return inputs, None, 0
        # Dense batch samples are independent; a CP cut is not a document reset.
        return torch.cat((halo, inputs), dim=1), None, halo.shape[1]
    if halo is None:
        return inputs, info.local_offsets, 0
    prefix = min(width - 1, info.preceding_sample_tokens)
    # The empty slice preserves a zero halo gradient when a real document resets.
196
197
198
199
200
201
202
203
204
        raise ValueError("Fused convolution input, weight and bias must be on the same device.")
    if info is not None and inputs.shape[:2] != (1, info.length):
        raise ValueError("Packed convolution expects [1,T,C] matching its token interval.")
    if halo is not None:
        _validate_fused_history(inputs, halo, weight.shape[-1])


def _validate_fused_history(
    inputs: torch.Tensor,
205
206
207
208
209
210
211
212
    halo: torch.Tensor,
    width: int,
) -> None:
    """Check the received history layout for dense and packed inputs."""
    if halo.shape != (inputs.shape[0], width - 1, inputs.shape[-1]):
        raise ValueError("Fused convolution halo has an incompatible shape.")
    if halo.dtype != inputs.dtype or halo.device != inputs.device:
        raise ValueError("Fused convolution halo must match the input dtype and device.")
353
354
355
356
357
358
359
360
361
        ImportError: If an explicitly selected optional kernel package is unavailable.
    """
    validate_conv_backend(backend)
    if inputs.ndim != 3 or inputs.shape[:2] != (1, info.length):
        raise ValueError("Packed convolution expects [1,T,C] matching its token interval.")
    channels = inputs.shape[-1]
    if (
        convolution.groups != convolution.in_channels
        or convolution.out_channels != convolution.in_channels
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        convolution.groups != convolution.in_channels
        or convolution.out_channels != convolution.in_channels
        or convolution.stride != (1,)
    ):
        raise ValueError("Packed convolution requires a stride-one depthwise Conv1d.")
    if weight is None:
        weight, bias = convolution.weight, convolution.bias
    width, dilation = convolution.kernel_size[0], convolution.dilation[0]
    if weight.shape != (channels, 1, width):
        raise ValueError("Packed convolution weight must match the local head channels.")
    halo_width = (width - 1) * dilation
    if halo is not None and halo.shape != (1, halo_width, channels):
        raise ValueError("Packed convolution halo has an incompatible shape.")
    if backend != "eager":
        return fused_causal_conv1d(
            inputs, weight, bias, info, halo, backend=backend, dilation=dilation,
        )
    if halo is None:
        halo = inputs.new_zeros((1, halo_width, channels))
408
409
410
411
412
413
414
415
416
        sequence_info: Immutable document metadata for this local token interval.
        backend: Explicit local operator implementation to dispatch.
    """
    if backend != "eager":
        return fused_causal_conv1d(
            tensor, convolution.weight, convolution.bias, sequence_info, halo,
            backend=backend, dilation=convolution.dilation[0])
    if sequence_info is not None:
        return packed_causal_conv1d(tensor, convolution, sequence_info, halo)
417
418
419
420
421
422
423
424
425
426
    if halo is None:
        conv_input = tensor.transpose(1, 2)
        padding = convolution.padding
    else:
        conv_input = torch.cat((halo, tensor), dim=1).transpose(1, 2)
        padding = 0
    output = F.conv1d(  # pylint: disable=not-callable
        input=conv_input,
        weight=convolution.weight,
        bias=convolution.bias,
hyper_parallel/components/modules/attention/gated_delta_net/cp_gated_delta_net.py
50
51
52
53
54
55
56
57
58
        """Retain the explicitly requested algorithm and deferred CP resources."""
        del module_fqn, context
        self.ulysses_degree = ulysses_degree
        if conv_backend is None and ulysses_degree == 1:
            conv_backend = "eager"
        super().__init__(config=config, module=module,
                         backend=backend, conv_backend=conv_backend, chunk_size=chunk_size, input_layout=input_layout)
        self.cp_rank, self.cp_size = 0, 1
        self.ulysses_size, self.state_size = 1, 1
69
70
71
72
73
74
75
76
77
        return prepare_linear_attention_input(hidden_states, options, self.cp_rank, self.cp_size)

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Expose the complete pipeline with internal state exchange owned by autograd."""
        return ParallelModuleSpec("attention.gdn.cp", "cp",
                                  {"execute_attention_pipeline": ("operands", "info")},
                                  validate=validate_linear_attention_layout)

    def bind_parallel(self, binding: Any) -> None:
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

        Args:
            binding: Resolved parallel binding containing the CP context.
        """
        if binding.cp_context is None:
            raise ValueError("GDN CP requires CPContext")
        self.cp_context = binding.cp_context
        self.cp_rank, self.cp_size = self.cp_context.rank, self.cp_context.size
        degree = self.cp_size if self.ulysses_degree is None else self.ulysses_degree
        if degree not in (1, self.cp_size):
            raise NotImplementedError("GDN supports pure Ulysses or P2P, not a mixed degree")
        self.ulysses_size, self.state_size = degree, self.cp_size // degree
        self.convolve_after_exchange = self.ulysses_degree is None or (1 < self.cp_size == degree)
        if self.convolve_after_exchange and (self.num_k_heads % degree or self.num_v_heads % degree):
            raise ValueError("GDN Ulysses degree must divide query and value heads")
        if not self.convolve_after_exchange and self.cp_size > 1 and self.backend != "triton":
            raise NotImplementedError("GDN state CP requires Triton; use local/pure Ulysses for other backends")

    def _exchange_raw_inputs(self, operands: tuple) -> tuple:
        """Exchange packed Q/K/V and gates before pure-Ulysses convolution."""
        mixed, beta, decay = operands
        if self.cp_size == 1:
            return mixed, beta, decay
        widths = (self.conv_dim // self.cp_size, self.num_v_heads // self.cp_size,
                  self.num_v_heads // self.cp_size)
        chunks = [tensor.split(width, dim=-1) for tensor, width in zip((mixed, beta, decay), widths)]
        packed = torch.cat([torch.cat(parts, dim=-1) for parts in zip(*chunks)], dim=-1).contiguous()
        packed = exchange_sequence_heads(packed, self.cp_context.mesh, split_dim=2, concat_dim=1)
        return packed.split(widths, dim=-1)

    def _local_conv_parameter(self, parameter: torch.Tensor | None) -> torch.Tensor | None:
        if parameter is None:
            return None
        width = self.conv_dim // self.cp_size
        return parameter.narrow(0, self.cp_rank * width, width)

    def _convolve_local_heads(self, mixed: torch.Tensor, info: PackedSequenceInfo | None) -> torch.Tensor:
        conv = self.conv1d
        weight, bias = self._local_conv_parameter(conv.weight), self._local_conv_parameter(conv.bias)
        if info is not None:
            return packed_causal_conv1d(mixed, conv, info, weight=weight, bias=bias, backend=self.conv_backend)
        if self.conv_backend != "eager":
            return fused_causal_conv1d(mixed, weight, bias, backend=self.conv_backend, dilation=conv.dilation[0])
        output = F.conv1d(mixed.transpose(1, 2), weight, bias, stride=conv.stride,
                          padding=conv.padding, dilation=conv.dilation, groups=mixed.shape[-1])
        return F.silu(output[:, :, :mixed.shape[1]]).transpose(1, 2)

    def execute_attention_pipeline(self, operands: tuple, info: PackedSequenceInfo | None) -> torch.Tensor:
        """Exchange tokens before pure-U convolution, or exchange states inside P2P autograd.
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
            info: Immutable packed-sequence metadata, or None for dense input.
        """
        if self.cp_context is None:
            raise RuntimeError("Bind GDN CP resources before forward")
        if self.convolve_after_exchange:
            mixed, beta, decay = self._exchange_raw_inputs(operands)
            info = None if info is None else info.ulysses(self.cp_size, self.cp_rank)
            mixed = self._convolve_local_heads(mixed, info)
            heads = self.num_v_heads // self.cp_size
            a_log = self.A_log.narrow(0, self.cp_rank * heads, heads)
            dt_bias = self.dt_bias.narrow(0, self.cp_rank * heads, heads)
            inputs = self.prepare_core_inputs(mixed, beta, decay, self.cp_size, a_log, dt_bias)
            output = self.run_local_core(inputs, info)
            return (output if self.cp_size == 1 else
                    exchange_sequence_heads(output, self.cp_context.mesh, split_dim=1, concat_dim=2))
        mixed, beta, decay = operands
        mixed, = causal_convolutions_with_halo((mixed,), (self.conv1d,), self.cp_context.mesh,
                                               self.cp_rank, self.cp_size, sequence_info=info,
                                               backend=self.conv_backend)
        inputs = self.prepare_core_inputs(mixed, beta, decay)
        if self.backend == "triton":
            if not is_triton_gdn_available(*inputs):
                raise RuntimeError("GDN P2P Triton requires the fixed NPU BF16 K=V=128 contract")
            return triton_state_gdn(*inputs, self.cp_context.mesh, self.cp_rank, self.cp_size, sequence_info=info)
        return self.run_local_core(inputs, info)


def _global_peer_rank(cp_mesh: DeviceMesh, local_rank: int) -> int:
    """Map a CP-local rank index to its global distributed rank."""
    return int(cp_mesh.rank_list[local_rank])


def _l2norm_torch(x: torch.Tensor, dim: int = -1, eps: float = 1e-6) -> torch.Tensor:
    """Match the pure torch GDN reference l2norm helper."""
    return (x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)).to(x.dtype)


def _prepare_gdn_forward_send(key_norm, w, u, g_cumsum, send_next, sequence_info,
                              recv_buffer, recv_handle, cp_group, next_rank):
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def _prepare_gdn_forward_send(key_norm, w, u, g_cumsum, send_next, sequence_info,
                              recv_buffer, recv_handle, cp_group, next_rank):
    """Forward the tail summary before consuming the prepared local chunks."""
    # These helpers load optional Triton kernels only when the fused path runs.
    from hyper_parallel.components.functional.gated_delta_net_triton import (  # pylint: disable=import-outside-toplevel
        chunk_gated_delta_rule_state_summary_fwd,
    )
    initial_state = None
    state_ext = None
    transition = None
    if send_next:
        tail = slice(None) if sequence_info is None else sequence_info.tail
        state_ext, transition = chunk_gated_delta_rule_state_summary_fwd(
            key_norm[:, tail], w[:, tail], u[:, tail], g_cumsum[:, tail],
            output_transition=sequence_info is None or sequence_info.transfer_active,
        )

    if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active):
        recv_handle.wait()
        initial_state = recv_buffer
        recv_handle = None

    send_buffer = None
    send_handle = None
    if send_next:
        send_buffer = apply_gdn_state_summary(
            state_ext,
            transition,
            initial_state if transition is not None else None,
        ).contiguous()
        send_handle = dist.isend(send_buffer, dst=next_rank, group=cp_group)

    if recv_handle is not None:
        recv_handle.wait()
        initial_state = recv_buffer
    return initial_state, transition, send_buffer, send_handle


def _finish_gdn_local_backward(ctx, query, key, value, g_cumsum, beta, matrix_a,
                               w, h, v_new, dv, dh, grad_output, cu_seqlens):
206
207
208
209
210
211
212
213
214
215
216
217
218
def _finish_gdn_local_backward(ctx, query, key, value, g_cumsum, beta, matrix_a,
                               w, h, v_new, dv, dh, grad_output, cu_seqlens):
    """Finish local gradients after the outgoing state gradient is in flight."""
    # These helpers load optional Triton kernels only when the fused path runs.
    from hyper_parallel.components.functional.gated_delta_net_triton import (  # pylint: disable=import-outside-toplevel
        chunk_gated_delta_rule_bwd_finish_saved,
    )
    empty = query.new_empty(0)
    dq, dk, dv, dg, dbeta = chunk_gated_delta_rule_bwd_finish_saved(
        query,
        key,
        query,
        key,
231
232
233
234
235
236
237
238
239
        ctx.scale,
        use_qk_l2norm_in_kernel=False,
        cu_seqlens=cu_seqlens,
    )
    return dq, dk, dv, dg, dbeta


class _GDNStateP2PTritonFunction(torch.autograd.Function):
    """Pipeline fused affine GDN states over sequence-sharded CP ranks."""
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
            next_rank: Global rank receiving the outgoing state.
            sequence_info: Immutable document metadata for this local token interval.
        """
        # Optional Triton kernels must stay unloaded for ordinary CPU imports.
        from hyper_parallel.components.functional.gated_delta_net_triton import (  # pylint: disable=import-outside-toplevel
            chunk_gated_delta_rule_fwd_apply_state_saved, chunk_gated_delta_rule_fwd_output_saved,
            chunk_gated_delta_rule_fwd_prepare_saved,
        )

        receive_previous = cp_rank > 0 and (sequence_info is None or sequence_info.continues_previous)
        send_next = cp_rank < cp_size - 1 and (sequence_info is None or sequence_info.continues_next)
        initial_state = None
        recv_buffer = None
        recv_handle = None
        if receive_previous:
            recv_buffer = torch.empty(
                (query.shape[0], query.shape[2], query.shape[3], value.shape[3]),
                device=query.device,
                dtype=torch.float32,
            )
            recv_handle = dist.irecv(recv_buffer, src=prev_rank, group=cp_group)

        cu_seqlens = None if sequence_info is None else sequence_info.materialize(query.device, 64).cu_seqlens
        (
            query_norm, key_norm, _, _, g_cumsum, matrix_a, w, u, scale,
        ) = chunk_gated_delta_rule_fwd_prepare_saved(
            query, key, value, g, beta,
            use_qk_l2norm_in_kernel=False,
296
297
298
299
300
301
302
303
304
305
306
307
308
            use_qk_l2norm_in_kernel=False,
            cu_seqlens=cu_seqlens,
        )

        initial_state, transition, send_buffer, send_handle = _prepare_gdn_forward_send(
            key_norm, w, u, g_cumsum, send_next, sequence_info,
            recv_buffer, recv_handle, cp_group, next_rank,
        )
        h, v_new, _ = chunk_gated_delta_rule_fwd_apply_state_saved(
            key_norm, g_cumsum, w, u,
            initial_state=initial_state if sequence_info is None else sequence_info.first_state(initial_state),
            output_final_state=False,
            cu_seqlens=cu_seqlens,
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
            initial_state=initial_state if sequence_info is None else sequence_info.first_state(initial_state),
            output_final_state=False,
            cu_seqlens=cu_seqlens,
        )
        output = chunk_gated_delta_rule_fwd_output_saved(
            query_norm, key_norm, g_cumsum, h, v_new, scale,
            cu_seqlens=cu_seqlens,
        ).to(query.dtype)

        if send_handle is not None:
            send_handle.wait()
        del send_buffer

        empty = query.new_empty(0)
        ctx.save_for_backward(
            query_norm,
            key_norm,
            value,
            g_cumsum,
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
            initial_state if initial_state is not None else empty,
            transition if transition is not None else empty,
            cu_seqlens if cu_seqlens is not None else query.new_empty(0, dtype=torch.int64),
        )
        ctx.sequence_info = sequence_info
        ctx.has_initial_state = initial_state is not None
        ctx.has_transition = transition is not None
        ctx.receive_previous = receive_previous
        ctx.send_next = send_next
        ctx.cp_rank = cp_rank
        ctx.cp_size = cp_size
        ctx.cp_group = cp_group
        ctx.prev_rank = prev_rank
        ctx.next_rank = next_rank
        ctx.scale = scale
        return output

    @staticmethod
    def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:  # pylint: disable=too-many-locals
        """Backpropagate local GDN tensors and the state gradient wavefront.
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
            ctx: Autograd context owning tensors and communication metadata for this invocation.
            grad_output: Gradient of the local operator output.
        """
        # Optional Triton kernels must stay unloaded for ordinary CPU imports.
        from hyper_parallel.components.functional.gated_delta_net_triton import (  # pylint: disable=import-outside-toplevel
            chunk_gated_delta_rule_bwd_prepare_saved, chunk_gated_delta_rule_bwd_state_saved,
        )
        from hyper_parallel.components.functional.gated_delta_net_triton import (  # pylint: disable=import-outside-toplevel
            chunk_gated_delta_rule_state_gradient_summary_bwd,
        )

        (
            query,
            key,
            value,
            g_cumsum,
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
            initial_state,
            transition,
            saved_cu_seqlens,
        ) = ctx.saved_tensors
        sequence_info = ctx.sequence_info
        cu_seqlens = None if sequence_info is None else saved_cu_seqlens
        if not ctx.has_initial_state:
            initial_state = None

        grad_final_state = None
        recv_handle = None
        if ctx.send_next:
            recv_buffer = torch.empty(
                (query.shape[0], query.shape[2], query.shape[3], value.shape[3]),
                device=grad_output.device,
                dtype=torch.float32,
            )
            recv_handle = dist.irecv(
                recv_buffer,
                src=ctx.next_rank,
                group=ctx.cp_group,
            )
386
387
388
389
390
391
392
393
394
395
                src=ctx.next_rank,
                group=ctx.cp_group,
            )

        kernel_initial = initial_state if sequence_info is None else sequence_info.first_state(initial_state)
        w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare_saved(
            query,
            key,
            value,
            g_cumsum,
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
            ctx.scale,
            cu_seqlens=cu_seqlens,
        )

        grad_state_ext = None
        if ctx.receive_previous:
            head = slice(None) if sequence_info is None else sequence_info.head
            grad_state_ext = chunk_gated_delta_rule_state_gradient_summary_bwd(
                query[:, head], key[:, head], w[:, head], g_cumsum[:, head],
                grad_output[:, head], dv[:, head], ctx.scale)

        if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active):
            recv_handle.wait()
            grad_final_state = recv_buffer
            recv_handle = None

        send_buffer = None
        send_handle = None
        if ctx.receive_previous:
            send_buffer = apply_gdn_state_gradient_summary(
                grad_state_ext,
                transition,
                grad_final_state if ctx.has_transition else None,
            ).contiguous()
            send_handle = dist.isend(
                send_buffer,
                dst=ctx.prev_rank,
                group=ctx.cp_group,
            )
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
                dst=ctx.prev_rank,
                group=ctx.cp_group,
            )

        if recv_handle is not None:
            recv_handle.wait()
            grad_final_state = recv_buffer
        kernel_grad_final = grad_final_state if sequence_info is None else sequence_info.last_state(grad_final_state)
        # Rebind dv here so the prepared local gradient is released before finalize.
        dh, _, dv = chunk_gated_delta_rule_bwd_state_saved(
            query, key, g_cumsum, w, kernel_initial, kernel_grad_final,
            grad_output, dv, ctx.scale, cu_seqlens=cu_seqlens,
        )
        dq, dk, dv, dg, dbeta = _finish_gdn_local_backward(
            ctx, query, key, value, g_cumsum, beta, matrix_a,
            w, h, v_new, dv, dh, grad_output, cu_seqlens,
        )

        if send_handle is not None:
            send_handle.wait()
        return dq, dk, dv, dg, dbeta, None, None, None, None, None, None


def triton_state_gdn(
    query: torch.Tensor,
469
470
471
472
473
474
475
476
477
478
        cp_rank: Local rank in that mesh.
        cp_size: Number of state ranks.
        sequence_info: Immutable local document interval, or None for dense input.
    """
    if cp_size == 1:
        output, _ = chunk_gated_delta_rule(
            query,
            key,
            value,
            g=g,
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
            use_qk_l2norm_in_kernel=True,
            backend="triton",
            cu_seqlens=None if sequence_info is None else sequence_info.materialize(query.device, 64).cu_seqlens,
        )
        return output

    query = _l2norm_torch(query)
    key = _l2norm_torch(key)
    prev_rank = _global_peer_rank(cp_mesh, cp_rank - 1) if cp_rank > 0 else -1
    next_rank = (
        _global_peer_rank(cp_mesh, cp_rank + 1) if cp_rank < cp_size - 1 else -1
    )
    return _GDNStateP2PTritonFunction.apply(
        query,
        key,
        value,
        g,
hyper_parallel/components/modules/attention/gated_delta_net/gated_delta_net.py
67
68
69
70
71
72
73
74
75
                 chunk_size: int = 64, input_layout: str = "BSH") -> None:
        """Construct local parameters or convert source QKV rows, retaining checkpoint names."""
        super().__init__()
        if (config is None) == (module is None):
            raise ValueError("GDN requires exactly one of config or module")
        self.config = config if module is None else getattr(module, "config", None)
        self.backend = backend
        self.conv_backend = validate_conv_backend(backend if conv_backend is None else conv_backend)
        self.chunk_size, self.input_layout = chunk_size, input_layout
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        else:
            self._adopt_source(module)
        validate_causal_convolution(self.conv1d)
        if self.num_v_heads % self.num_k_heads:
            raise ValueError("GDN value heads must be divisible by query heads")
        self._configure_qkv_layout(module)
        if self.backend not in ("eager", "triton", "ascendc"):
            raise ValueError("GDN backend must be eager, triton or ascendc")
        if self.backend != "eager" and (self.head_k_dim != 128 or self.head_v_dim != 128 or chunk_size != 64):
            raise ValueError("Fused GDN requires K=V=128 and chunk_size=64")
        if self.activation not in ("silu", "swish"):
            raise NotImplementedError("GDN family implements SiLU/Swish convolution")

    def __deepcopy__(self, memo: dict) -> nn.Module:
        """Retain pre-binding model-copy behavior without copying process groups."""
        return copy_unbound_linear_attention(self, memo)
124
125
126
127
128
129
130
131
132
                  "norm", "out_proj", "out_proj_input")
        dimensions = ("num_k_heads", "num_v_heads", "head_k_dim", "head_v_dim", "key_dim", "value_dim", "conv_dim")
        missing = [name for name in owners[:-1] + dimensions if not hasattr(module, name)]
        if missing:
            raise TypeError(f"GDN source is missing {missing}")
        adopt_source_parameters(self, module, owners)
        for name in dimensions:
            setattr(self, name, getattr(module, name))
        self.hidden_size = self.in_proj_qkv.in_features
167
168
169
170
171
172
173
174
175
        Returns:
            Source-checkpoint transforms; native construction already uses grouped rows.
        """
        if not self._convert_source_qkv:
            return []
        names = [f"{owner}.{suffix}" for owner in ("in_proj_qkv", "conv1d")
                 for suffix in ("weight", "bias") if getattr(getattr(self, owner), suffix, None) is not None]
        return [WeightConverter(source_patterns=name, target_patterns=name,
                                operations=[self._qkv_conversion()]) for name in names]
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
                                operations=[self._qkv_conversion()]) for name in names]

    def reset_parameters(self) -> None:
        """Initialize direct/meta parameters without resetting converted sources."""
        if not self._config_initialization:
            return
        for child in self.children():
            if isinstance(child, (nn.Linear, nn.Conv1d)):
                child.reset_parameters()
        with torch.no_grad():
            self.A_log.uniform_(0, 16).log_()
            self.dt_bias.fill_(1)
            self.norm.weight.fill_(1)

    def project_inputs(self, hidden_states: torch.Tensor) -> tuple:
        """Keep output-gate tokens local while producing raw recurrence operands.
264
265
266
267
268
269
270
271
272
        batch, tokens = output.shape[:2]
        output = self.norm(output.reshape(-1, self.head_v_dim), gate.reshape(-1, self.head_v_dim))
        output = output.reshape(batch, tokens, self.value_dim)
        if hasattr(self, "out_proj_input"):
            output = self.out_proj_input(output)
        return self.out_proj(output)

    def prepare_input(self, hidden_states: torch.Tensor, options: dict) -> tuple:
        """Adapt local dense/flat input; CP members resolve their own token interval.
297
298
299
300
301
302
303
304
305
306
307
308
309
310
            cache_params: Inference cache; training-family execution requires None.
            attention_mask: Optional source-model mask; packed boundaries carry document resets.
        """
        if cache_params is not None or kwargs.get("use_cache", False):
            raise NotImplementedError("GDN family supports training without recurrent cache")
        hidden_states, info, is_flat_input = self.prepare_input(hidden_states, kwargs)
        if attention_mask is not None:
            if attention_mask.ndim != 2 or tuple(attention_mask.shape) != tuple(hidden_states.shape[:2]):
                raise ValueError("GDN expects a local two-dimensional padding mask")
            hidden_states = hidden_states * attention_mask[:, :, None].to(hidden_states.dtype)
        operands, gate = self.project_inputs(hidden_states)
        del hidden_states
        output = self.execute_attention_pipeline(operands, info)
        del operands
hyper_parallel/components/modules/attention/gated_delta_net/gated_delta_net_family.py
34
35
36
37
38
39
40
41

def _validate_gdn_protocol(cp, degree, backend):
    """Reject unimplemented combinations before creating communication groups."""
    if cp > 1 and degree not in (1, cp):
        raise NotImplementedError("GDN currently supports pure Ulysses or state P2P, not their hybrid")
    if cp > degree and backend != "triton":
        raise NotImplementedError("GDN state CP requires Triton; eager and Ascend C support local/pure Ulysses")

47
48
49
50
51
52
53
54
55
    cp = member.axis_sizes["cp"]
    degree = member.arguments.get("ulysses_degree", 1)
    degree = cp if degree is None else degree
    if (not isinstance(degree, int) or isinstance(degree, bool)) or degree < 1 or (cp > 1 and cp % degree):
        raise ValueError("ulysses_degree must be a positive divisor of CP size")
    source = config if module is None else module
    kh = getattr(source, "num_k_heads", None) if module is not None else source.linear_num_key_heads
    vh = getattr(source, "num_v_heads", None) if module is not None else source.linear_num_value_heads
    head_degree = member.axis_sizes["tp"] * (degree if cp > 1 else 1)
hyper_parallel/components/modules/attention/kimi_delta_attention/cp_kimi_delta_attention.py
60
61
62
63
64
65
66
67
68
        # Preserve the established post-A2A convolution for the degree=None request.
        # Topology is tracked separately as CP = ulysses_size * state_size.
        self.convolve_after_exchange = ulysses_degree is None
        if conv_backend is None and not self.convolve_after_exchange:
            conv_backend = "ascendc" if backend == "ascendc" else "eager"
        super().__init__(config=config, module=module,
                         backend=backend, conv_backend=conv_backend, chunk_size=chunk_size, input_layout=input_layout)
        self.ulysses_degree = ulysses_degree
        self.state_cp_method = state_cp_method
85
86
87
88
89
90
91
92
93
        return prepare_linear_attention_input(hidden_states, options, self.cp_rank, self.cp_size)

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Declare the stage containing both token exchange and nested state exchange."""
        return ParallelModuleSpec("attention.kda.cp", "cp",
                                  {"execute_attention_pipeline": ("hidden_states", "info")},
                                  validate=validate_linear_attention_layout)

    def bind_parallel(self, binding: Any) -> None:
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

        Args:
            binding: Resolved parallel binding containing the CP context.
        """
        if binding.cp_context is None:
            raise ValueError("KDA CP requires CPContext")
        self.cp_context = binding.cp_context
        self.cp_rank, self.cp_size = self.cp_context.rank, self.cp_context.size
        degree = self.cp_size if self.convolve_after_exchange else self.ulysses_degree
        if (not isinstance(degree, int) or isinstance(degree, bool)) or degree < 1 or self.cp_size % degree:
            raise ValueError("KDA Ulysses degree must divide CP size")
        if self.num_heads % degree or self.num_v_heads % degree:
            raise ValueError("KDA Ulysses degree must divide query and value heads")
        self.ulysses_size, self.state_size = degree, self.cp_size // degree
        if self.state_size == 1:
            # Pure U has no state exchange. Preserve the requested convolution position.
            self.ulysses_mesh = self.cp_context.mesh if degree > 1 else None
            self.ulysses_rank = self.cp_rank
            return
        self.state_mesh = self.cp_context.mesh
        if degree > 1:
            hybrid = split_kda_mesh(self.state_mesh, degree, ("kda_state", "kda_ulysses"))
            self.ulysses_mesh = hybrid["kda_ulysses"]
            self.ulysses_rank = self.ulysses_mesh.get_local_rank()
            self.state_mesh = hybrid["kda_state"]
        self.state_cp = build_kda_state_cp(self.state_mesh, self.state_cp_method, self.allgather_group_size)

    def _run_state_backend(self, operands: tuple, info: PackedSequenceInfo | None,
                           a_log: torch.Tensor, dt_bias: torch.Tensor) -> torch.Tensor:
        """Inject states inside backend autograd, reusing the local path at state degree one."""
        if self.state_size == 1:
            return self.run_local_core(operands, info, a_log, dt_bias)
        size, rank = self.state_size, self.state_mesh.get_local_rank()
        if self.backend == "ascendc":
            # Native CP must not import optional Triton summary kernels.
            from .cp_state_ascendc import ascendc_state_kda  # pylint: disable=import-outside-toplevel
            # FSDP may expose BF16 compute weights; native gates require FP32, as in the local core.
            return ascendc_state_kda(
                *operands, a_log=a_log.float(), dt_bias=dt_bias.float(), lower_bound=self.lower_bound,
                state_cp=self.state_cp, cp_mesh=self.state_mesh, sequence_info=info)
        if self.backend != "triton":
            raise NotImplementedError("KDA state CP requires Triton or Ascend C; eager supports local/pure Ulysses")
        ranks = self.state_mesh.rank_list
        return triton_state_kda(
            *operands, a_log=a_log.float(), dt_bias=dt_bias.float(), lower_bound=self.lower_bound,
            chunk_size=self.chunk_size, safe_gate=self.safe_gate,
            cp_group=self.state_mesh.get_group(), cp_rank=rank, cp_size=size,
            prev_rank=int(ranks[max(rank - 1, 0)]), next_rank=int(ranks[min(rank + 1, size - 1)]),
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
            info: Real document boundaries for this rank's physical token interval.
            a_log: Optional parameter view used by the projected-stage caller.
            dt_bias: Optional parameter view used by the projected-stage caller.
        """
        a_log = self.A_log if a_log is None else a_log
        dt_bias = self.dt_bias if dt_bias is None else dt_bias
        if self.ulysses_mesh is None:
            return self._run_state_backend(operands, info, a_log, dt_bias)
        inputs = tuple(exchange_sequence_heads(tensor, self.ulysses_mesh, split_dim=2, concat_dim=1)
                       for tensor in operands)
        heads = self.num_v_heads // self.ulysses_size
        a_log = a_log.reshape(self.num_v_heads).narrow(0, self.ulysses_rank * heads, heads).contiguous()
        dt_bias = dt_bias.reshape(self.num_v_heads, self.head_k_dim).narrow(
            0, self.ulysses_rank * heads, heads).contiguous()
        info = None if info is None else info.ulysses(self.ulysses_size, self.ulysses_rank)
        output = self._run_state_backend(inputs, info, a_log, dt_bias)
        return exchange_sequence_heads(output, self.ulysses_mesh, split_dim=1, concat_dim=2)

    def _exchange_raw_inputs(self, operands: tuple) -> tuple:
        if self.cp_size == 1:
            return operands
        widths = (self.key_dim, self.key_dim, self.value_dim,
                  self.num_v_heads * self.head_k_dim, self.num_v_heads)
        widths = tuple(width // self.cp_size for width in widths)
        chunks = [tensor.split(width, dim=-1) for tensor, width in zip(operands, widths)]
        packed = torch.cat([torch.cat(parts, dim=-1) for parts in zip(*chunks)], dim=-1).contiguous()
        packed = exchange_sequence_heads(packed, self.cp_context.mesh, split_dim=2, concat_dim=1)
        return packed.split(widths, dim=-1)

    def _convolve_local_heads(self, operands: tuple, info: PackedSequenceInfo | None) -> tuple:
        """Convolve each local head shard with its matching source weight slice."""
        query, key, value, gate, beta = operands
        if not self.use_short_conv:
            return *(F.silu(tensor) for tensor in (query, key, value)), gate, beta
        convolved = []
        for tensor, conv in zip((query, key, value), (self.q_conv1d, self.k_conv1d, self.v_conv1d)):
            channels = tensor.shape[-1]
            start = self.cp_rank * channels
            weight = conv.weight.narrow(0, start, channels)
            bias = None if conv.bias is None else conv.bias.narrow(0, start, channels)
            if info is not None:
                output = packed_causal_conv1d(tensor, conv, info, weight=weight, bias=bias, backend=self.conv_backend)
            elif self.conv_backend != "eager":
                output = fused_causal_conv1d(tensor, weight, bias, backend=self.conv_backend,
                                             dilation=conv.dilation[0])
            else:
                output = F.conv1d(tensor.transpose(1, 2), weight, bias, stride=conv.stride,
                                  padding=conv.padding, dilation=conv.dilation, groups=channels)
                output = F.silu(output[:, :, :tensor.shape[1]].transpose(1, 2))
            convolved.append(output)
        return *convolved, gate, beta

    def execute_attention_pipeline(self, hidden_states: torch.Tensor, info: PackedSequenceInfo | None) -> tuple:
        """Preserve pure-U post-exchange convolution and state-CP pre-exchange halos.
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
            info: Immutable packed-sequence metadata, or None for dense input.
        """
        if self.cp_context is None:
            raise RuntimeError("Bind KDA CP resources before forward")
        if not self.training:
            raise NotImplementedError("KDA CP currently supports training only")
        projected = self.project_inputs(hidden_states)
        if self.convolve_after_exchange:
            gate, beta = self.project_state_gates(hidden_states)
            output_gate = self.project_output_gate(hidden_states)
            operands = (*projected, gate, beta)
            exchanged_info = None if info is None else info.ulysses(self.cp_size, self.cp_rank)
            operands = self._exchange_raw_inputs(operands)
            operands = self.shape_inputs(self._convolve_local_heads(operands, exchanged_info), self.cp_size)
            heads = self.num_v_heads // self.cp_size
            a_log = self.A_log.reshape(self.num_v_heads).narrow(0, self.cp_rank * heads, heads)
            dt_bias = self.dt_bias.reshape(self.num_v_heads, self.head_k_dim).narrow(0, self.cp_rank * heads, heads)
            output = self._run_state_backend(operands, exchanged_info, a_log, dt_bias)
            return exchange_sequence_heads(output, self.cp_context.mesh, split_dim=1, concat_dim=2), output_gate
        query, key, value = projected
        if self.use_short_conv:
            query, key, value = causal_convolutions_with_halo(
                (query, key, value), (self.q_conv1d, self.k_conv1d, self.v_conv1d),
                self.cp_context.mesh, self.cp_rank, self.cp_size, sequence_info=info, backend=self.conv_backend)
        else:
            query, key, value = (F.silu(tensor) for tensor in (query, key, value))
        gate, beta = self.project_state_gates(hidden_states)
        output_gate = self.project_output_gate(hidden_states)
        output = self.run_state_core(self.shape_inputs((query, key, value, gate, beta)), info)
        return output, output_gate


def _validate_mesh_order(mesh: DeviceMesh) -> None:
    """Prevent collective slots from being mistaken for chronological positions."""
255
256
257
258
259
260
261
262
263
264
265
    Returns:
        Two-dimensional submesh attached to the original root.
    """
    if mesh.ndim != 1 or not isinstance(degree, int) or isinstance(degree, bool):
        raise ValueError("KDA mesh splitting requires a 1-D mesh and integer degree.")
    if degree < 1 or mesh.size() % degree:
        raise ValueError("KDA split degree must be positive and divide the CP size.")
    _validate_mesh_order(mesh)
    # Group creation uses WORLD; every rank must derive the same sibling groups.
    root = mesh._get_root_mesh()  # pylint: disable=protected-access
    if root.size() != dist.get_world_size():
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309

    Returns:
        State executor with an invocation-owned cache, or None for the P2P/local path.
    """
    if protocol not in ("p2p", "allgather", "grouped_allgather_p2p", "recursive_doubling"):
        raise ValueError(f"Unknown KDA state_cp_method: {protocol!r}.")
    if not isinstance(allgather_group_size, int) or isinstance(allgather_group_size, bool) or allgather_group_size < 1:
        raise ValueError("KDA allgather_group_size must be a positive integer.")
    if protocol != "grouped_allgather_p2p" and allgather_group_size != 1:
        raise ValueError("KDA allgather_group_size is only valid for grouped_allgather_p2p.")
    if protocol == "p2p":
        return None
    ranks = tuple(mesh.rank_list)
    rank, size = mesh.get_local_rank(), mesh.size()
    if protocol == "recursive_doubling":
        return KDAStateRecursiveDoubling(mesh.get_group(), rank, ranks) if size > 1 else None
    if protocol == "allgather":
        _validate_mesh_order(mesh)
        return KDAStateAllGather(mesh.get_group(), rank, size)
    if size % allgather_group_size:
        raise ValueError("KDA allgather_group_size must divide the state CP size.")
    if allgather_group_size == 1:
        return None
    if allgather_group_size == size:
        _validate_mesh_order(mesh)
        return KDAStateAllGather(mesh.get_group(), rank, size)
    split = split_kda_mesh(mesh, allgather_group_size, ("kda_outer", "kda_group"))
    return KDAStateAllGatherP2P(
        mesh.get_group(), split["kda_group"].get_group(), rank, ranks, allgather_group_size)


def _gather_maps(state: torch.Tensor, matrix: torch.Tensor, group: Any, size: int) -> torch.Tensor:
307
308
309
310
311
312
313
314
315
316
317
318


def _gather_maps(state: torch.Tensor, matrix: torch.Tensor, group: Any, size: int) -> torch.Tensor:
    """Pack validated local summaries for one invocation; the caller owns the gathered storage."""
    packed = torch.cat((state, matrix), dim=-1)
    output = packed.new_empty((size * packed.shape[0], *packed.shape[1:]))
    dist.all_gather_into_tensor(output, packed, group=group)
    return output.view(size, *packed.shape)


class KDAStateAllGather:
    """Gather S/M forward and G/M backward; only local M survives forward."""
319
320
321
322
323
324
325
326
327

    def __init__(self, group: Any, rank: int, size: int) -> None:
        """Bind precreated communication metadata, without tensor workspaces."""
        if not isinstance(size, int) or isinstance(size, bool) or size < 1 or not 0 <= rank < size:
            raise ValueError("AllGather requires a positive size and valid local rank.")
        self.group, self.rank, self.size = group, rank, size

    def gather_packed(self, packed: torch.Tensor) -> torch.Tensor:
        """Collect native [1,H,128,256] summaries without a second packing copy.
331
332
333
334
335
336
337
338
339
340

        Args:
            packed: Packed state and transition tensors for the scan.
        """
        output = packed.new_empty((self.size, *packed.shape[1:]))
        dist.all_gather_into_tensor(output, packed, group=self.group)
        return output

    def forward(self, state: torch.Tensor, matrix: torch.Tensor) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]:
        """Return the incoming state and this invocation's original local M.
347
348
349
350
351
352
353
354
355
356
357
358
            This rank's incoming recurrent state and a one-tensor local M cache.
        """
        validate_kda_state_summary(state, matrix)
        # The native driver uses transport only and must not import Triton.
        from hyper_parallel.components.functional.kimi_delta_attention_triton import (  # pylint: disable=import-outside-toplevel
            merge_affine_summaries,
        )
        maps = _gather_maps(state, matrix, self.group, self.size)
        return merge_affine_summaries(maps[..., :128], maps[..., 128:], self.rank, True), (matrix,)

    def backward(self, gradient: torch.Tensor, cache: tuple[torch.Tensor, ...]) -> torch.Tensor:
        """Collect new G with the saved local M and recover the outgoing gradient.
366
367
368
369
370
371
372
373
374
375
376
377
378
        """
        matrix, = cache
        validate_kda_state_summary(gradient, matrix)
        # Load optional Triton math only for this protocol implementation.
        from hyper_parallel.components.functional.kimi_delta_attention_triton import (  # pylint: disable=import-outside-toplevel
            merge_affine_summaries,
        )
        maps = _gather_maps(gradient, matrix, self.group, self.size)
        return merge_affine_summaries(maps[..., :128], maps[..., 128:], self.rank, False)


class KDAStateAllGatherP2P:
    """Use group-local gathers and an owner chain, retaining only each local M."""
381
382
383
384
385
386
387
388
389
                 ranks: tuple[int, ...], width: int) -> None:
        """Bind ranks already validated against the process-group order by the factory."""
        size = len(ranks)
        if not isinstance(width, int) or isinstance(width, bool) or width < 2 or size % width:
            raise ValueError("Grouped AllGather width must be >= 2 and divide the CP size.")
        if not 0 <= rank < size or len(set(ranks)) != size:
            raise ValueError("Grouped AllGather requires unique global ranks and a valid local rank.")
        self.group, self.intra, self.rank, self.width = group, intra_group, rank, width
        self.ranks = tuple(ranks)
392
393
394
395
396
397
398
399
400
401
402
403
404
        self.owner = self.block * width + width - 1

    def _receive(self, state: torch.Tensor, forward: bool) -> tuple[torch.Tensor, Any]:
        """Post the owner receive before gathering local summaries."""
        incoming = torch.zeros_like(state)
        recv_handle = None
        peer = self.owner - self.width if forward else self.owner + self.width
        if self.rank == self.owner and 0 <= peer < len(self.ranks):
            recv_handle = dist.irecv(incoming, src=self.ranks[peer], group=self.group)
        return incoming, recv_handle

    def forward(self, state: torch.Tensor, matrix: torch.Tensor) -> tuple[torch.Tensor, tuple[torch.Tensor, ...]]:
        """Relay ordered group scans and restore this rank's incoming state.
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
            This rank's incoming recurrent state and a one-tensor local M cache.
        """
        validate_kda_state_summary(state, matrix)
        # The native driver borrows groups without loading these Triton scans.
        from hyper_parallel.components.functional.kimi_delta_attention_triton import (  # pylint: disable=import-outside-toplevel
            scan_kda_affine_maps,
        )
        incoming, recv_handle = self._receive(state, True)
        maps = _gather_maps(state, matrix, self.intra, self.width)
        send_handle, send_state = None, None
        result = None
        if self.rank == self.owner:
            if recv_handle is not None:
                recv_handle.wait()
            if self.block + 1 < self.blocks:
                send_state, result = scan_kda_affine_maps(maps, incoming, range(self.width), True,
                                                        prefix_count=self.local)
                send_handle = dist.isend(send_state, dst=self.ranks[self.owner + self.width], group=self.group)
        if self.block > 0:
            dist.broadcast(incoming, src=self.ranks[self.owner], group=self.intra)
        if result is None:
            result, _ = scan_kda_affine_maps(maps, incoming, range(self.local), True)
        if send_handle is not None:
            send_handle.wait()
        return result, (matrix,)

    def backward(self, gradient: torch.Tensor, cache: tuple[torch.Tensor, ...]) -> torch.Tensor:
        """Regather G/M and reverse the owner chain with ordered state feedback.
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
        """
        matrix, = cache
        validate_kda_state_summary(gradient, matrix)
        # Keep the optional Triton implementation local to the selected path.
        from hyper_parallel.components.functional.kimi_delta_attention_triton import (  # pylint: disable=import-outside-toplevel
            scan_kda_affine_maps,
        )
        incoming, recv_handle = self._receive(gradient, False)
        maps = _gather_maps(gradient, matrix, self.intra, self.width)
        send_handle, send_state = None, None
        if self.rank == self.owner:
            if recv_handle is not None:
                recv_handle.wait()
            if self.block > 0:
                send_state, _ = scan_kda_affine_maps(maps, incoming, range(self.width - 1, -1, -1), False)
                send_handle = dist.isend(send_state, dst=self.ranks[self.owner - self.width], group=self.group)
        if self.block + 1 < self.blocks:
            dist.broadcast(incoming, src=self.ranks[self.owner], group=self.intra)
        result, _ = scan_kda_affine_maps(maps, incoming, range(self.width - 1, self.local, -1), False)
        if send_handle is not None:
            send_handle.wait()
        return result


def _validate_state_cp_inputs(
    query: torch.Tensor,
481
482
483
484
485
486
487
488
489
    cp_rank: int,
    cp_size: int,
) -> None:
    """Validate the fixed-shape KDA state CP backend before communication starts."""
    validate_triton_kda_inputs(
        query,
        key,
        value,
        gate,
492
493
494
495
496
497
498
499
500
501
        dt_bias,
        chunk_size=chunk_size,
        lower_bound=lower_bound,
    )
    if cp_size <= 0 or not 0 <= cp_rank < cp_size:
        raise ValueError(f"Invalid KDA state CP rank {cp_rank} for cp_size {cp_size}.")


def _prepare_packed_kda_summary(kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size):
    """Skip summaries with no consumer when the invocation supports absent tensors."""
499
500
501
502
503
504
505
506
507

def _prepare_packed_kda_summary(kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size):
    """Skip summaries with no consumer when the invocation supports absent tensors."""
    if state_cp is None and not send_next:
        return None, None
    state_shape = (kg.shape[0], u.shape[2], kg.shape[-1], u.shape[-1])
    transition = None
    if getattr(state_cp, "needs_state_summary", True):
        tail = sequence_info.tail
521
522
523
524
525
526
527
528
529
530
531
532
533


def _sequence_metadata(sequence_info, device, chunk_size):
    """Materialize one immutable packed plan for both intra-chunk and recurrent stages."""
    if sequence_info is None:
        return None, {}, {}
    plan = sequence_info.materialize(device, chunk_size)
    varlen = plan.kwargs()
    return plan, varlen, dict(varlen, chunk_offsets=plan.chunk_offsets)


def _exchange_forward(kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size,
                      cp_rank, cp_size, initial_state, recv_handle, next_rank, cp_group):
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573

def _exchange_forward(kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size,
                      cp_rank, cp_size, initial_state, recv_handle, next_rank, cp_group):
    """Produce only consumed summaries and keep an outgoing buffer alive until its send completes."""
    state_ext = None
    transition = None
    if sequence_info is not None:
        state_ext, transition = _prepare_packed_kda_summary(
            kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size,
        )
    else:
        if state_cp is None and cp_rank == 0 and cp_size > 1:
            # Zero entry uses S directly, and rank 0 has no reverse-state recipient.
            state_ext, transition = kda_state_summary_forward_from_prepared(
                kg, w, u, gate, chunk_size=chunk_size, output_transition=False,
            )
        elif state_cp is not None or cp_rank < cp_size - 1:
            state_ext, transition = kda_state_summary_forward_from_prepared(kg, w, u, gate, chunk_size=chunk_size)
    # A reset makes the outgoing summary independent of the incoming state.
    # Wait before apply only when it actually reads that state; local h still waits below.
    if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active):
        recv_handle.wait()
        recv_handle = None

    send_handle = None
    send_state = None
    state_cache = (transition,) if transition is not None else ()
    if state_cp is not None:
        initial_state, state_cache = state_cp.forward(state_ext, transition)
        transition = None
    elif send_next:
        summary_initial = initial_state if transition is not None else None
        final_state = apply_kda_state_summary(state_ext, transition, summary_initial)
        send_state = final_state.contiguous()
        send_handle = dist.isend(send_state, dst=next_rank, group=cp_group)

    if recv_handle is not None:
        recv_handle.wait()
    return initial_state, state_cache, send_handle, send_state


def _exchange_backward(ctx, query_gated, key_gated, w, gate, grad_output, grad_value_local,
                       state_shape, state_cache, grad_final_state, recv_handle):
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

def _exchange_backward(ctx, query_gated, key_gated, w, gate, grad_output, grad_value_local,
                       state_shape, state_cache, grad_final_state, recv_handle):
    """Produce G and reverse the state exchange without changing local backward arithmetic."""
    sequence_info = ctx.sequence_info
    grad_state_ext = None
    if ctx.state_cp is not None or ctx.receive_previous:
        if sequence_info is not None and not sequence_info.continues_previous:
            if not getattr(ctx.state_cp, "allows_absent_summaries", False):
                grad_state_ext = query_gated.new_zeros(state_shape, dtype=torch.float32)
        else:
            head = slice(None) if sequence_info is None else sequence_info.head
            grad_state_ext = kda_state_gradient_summary_from_prepared(
                query_gated[:, head], key_gated[:, head], w[:, head], gate[:, head],
                grad_output[:, head], grad_value_local[:, head], ctx.scale, chunk_size=ctx.chunk_size,
            )
    if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active):
        recv_handle.wait()
        recv_handle = None
    send_handle = None
    send_state_gradient = None
    if ctx.state_cp is not None:
        grad_final_state = ctx.state_cp.backward(grad_state_ext, state_cache)
    elif ctx.receive_previous:
        transition = state_cache[0] if state_cache else None
        summary_final_gradient = grad_final_state if transition is not None else None
        grad_initial_state = apply_kda_state_gradient_summary(grad_state_ext, transition, summary_final_gradient)
        send_state_gradient = grad_initial_state.contiguous()
        send_handle = dist.isend(send_state_gradient, dst=ctx.prev_rank, group=ctx.cp_group)

    if recv_handle is not None:
        recv_handle.wait()
    return grad_final_state, send_handle, send_state_gradient


class _KDAStateCPFunction(torch.autograd.Function):
    """Run shared local KDA and autograd with the selected state exchange."""
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
            cp_rank: Chronological index within the CP group.
            cp_size: Number of state partitions.
            state_cp: Executor returning an invocation cache; None selects P2P.
        """
        ops = get_fla_kda_staged_ops()
        bind_sequence = getattr(state_cp, "bind_sequence", None)
        if sequence_info is not None and bind_sequence is not None:
            state_cp = bind_sequence(
                sequence_info, state_shape=(query.shape[0], value.shape[2], query.shape[-1], value.shape[-1]))
        plan, varlen, recurrent_varlen = _sequence_metadata(sequence_info, query.device, chunk_size)

        # FLA consumes base-2 log gates: exp(x) = exp2(x / ln(2)).
        # Use the same conversion when recomputing gates in backward.
        rcp_ln2 = 1.4426950408889634

        query, key, value, gate_raw, beta_raw = (
            tensor.contiguous() for tensor in (query, key, value, gate_raw, beta_raw))
        query, query_rstd = ops.l2norm_fwd(query)
        key, key_rstd = ops.l2norm_fwd(key)
        beta = ops.fused_beta_sigmoid(beta_raw)
        gate = ops.kda_gate_chunk_cumsum(
            g=gate_raw, A_log=a_log, dt_bias=dt_bias, scale=rcp_ln2, chunk_size=chunk_size,
            lower_bound=lower_bound, **varlen,
        )

        state_shape = (query.shape[0], value.shape[2], query.shape[-1], value.shape[-1])
        receive_previous = cp_rank > 0 and (sequence_info is None or sequence_info.continues_previous)
        send_next = cp_rank < cp_size - 1 and (sequence_info is None or sequence_info.continues_next)
        initial_state = None
        recv_handle = None
        if state_cp is None and receive_previous:
            initial_state = torch.empty(state_shape, device=query.device, dtype=torch.float32)
            recv_handle = dist.irecv(initial_state, src=prev_rank, group=cp_group)

        w, u, _, kg, attention_qk, attention_kk = ops.chunk_kda_fwd_intra(
            q=query, k=key, v=value, gk=gate, beta=beta, scale=scale, chunk_size=chunk_size, safe_gate=safe_gate,
            disable_recompute=True, **varlen,
        )
        # The gated query is unused here and is recomputed in backward.
        del _
        initial_state, state_cache, send_handle, send_state = _exchange_forward(
            kg, w, u, gate, sequence_info, state_cp, send_next, chunk_size,
            cp_rank, cp_size, initial_state, recv_handle, next_rank, cp_group)
        kernel_initial_state = initial_state if sequence_info is None else sequence_info.first_state(initial_state)
        states, value_new, _ = ops.chunk_gated_delta_rule_fwd_h(
            k=kg, w=w, u=u, gk=gate, initial_state=kernel_initial_state,
            output_final_state=False, chunk_size=chunk_size, **recurrent_varlen,
        )
        # Local h was their last forward consumer on this stream.
        del w, u, kg, _
        output = ops.chunk_gla_fwd_o_gk(
            q=query, v=value_new, g=gate, A=attention_qk, h=states, scale=scale, chunk_size=chunk_size, **varlen,
        )
        if send_handle is not None:
            send_handle.wait()
        del send_state

        saved_initial_state = initial_state
        if saved_initial_state is None:
            saved_initial_state = query.new_empty(0, dtype=torch.float32)
        packed_tensors = () if plan is None else (
            plan.cu_seqlens, plan.chunk_indices, plan.chunk_offsets)
        ctx.save_for_backward(
            query, query_rstd, key, key_rstd, value, gate_raw, beta_raw, a_log, dt_bias, attention_qk,
            attention_kk, saved_initial_state, *state_cache, *packed_tensors,
        )
        ctx.scale = scale
        ctx.lower_bound = lower_bound
        ctx.chunk_size = chunk_size
        ctx.safe_gate = safe_gate
        ctx.cp_group = cp_group
        ctx.prev_rank = prev_rank
        ctx.next_rank = next_rank
        ctx.cp_rank = cp_rank
        ctx.cp_size = cp_size
        ctx.state_cp = state_cp
        ctx.state_cache_count = len(state_cache)
        ctx.receive_previous = receive_previous
        ctx.send_next = send_next
        ctx.sequence_info = sequence_info
        return output.to(value.dtype)

    @staticmethod
    def backward(  # pylint: disable=arguments-differ,too-many-locals
        ctx: Any,
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
        Args:
            ctx: Autograd context holding tensors and communication metadata.
            grad_output: Upstream gradient for the local token output.
        """
        ops = get_fla_kda_staged_ops()

        # FLA consumes base-2 log gates: exp(x) = exp2(x / ln(2)).
        # Use the same conversion when recomputing gates in backward.
        rcp_ln2 = 1.4426950408889634

        (
            query, query_rstd, key, key_rstd, value, gate_raw, beta_raw, a_log, dt_bias,
            attention_qk, attention_kk, saved_initial_state, *saved_tail,
        ) = ctx.saved_tensors
        state_cache = tuple(saved_tail[:ctx.state_cache_count])
        packed_tensors = saved_tail[ctx.state_cache_count:]
        sequence_info = ctx.sequence_info
        cu_seqlens = chunk_indices = chunk_offsets = None
        if sequence_info is not None:
            cu_seqlens, chunk_indices, chunk_offsets = packed_tensors
        varlen = {} if sequence_info is None else {"cu_seqlens": cu_seqlens, "chunk_indices": chunk_indices}
        recurrent_varlen = dict(varlen)
        if sequence_info is not None:
            recurrent_varlen["chunk_offsets"] = chunk_offsets
        initial_state = saved_initial_state if saved_initial_state.numel() else None
        kernel_initial_state = initial_state if sequence_info is None else sequence_info.first_state(initial_state)
        grad_output = grad_output.contiguous()

        grad_final_state = None
        recv_handle = None
        if ctx.state_cp is None and ctx.send_next:
            grad_final_state = torch.empty(
                (query.shape[0], value.shape[2], query.shape[-1], value.shape[-1]), device=query.device,
                dtype=torch.float32,
            )
            recv_handle = dist.irecv(grad_final_state, src=ctx.next_rank, group=ctx.cp_group)

        beta = ops.fused_beta_sigmoid(beta_raw)
        gate = ops.kda_gate_chunk_cumsum(
            g=gate_raw, A_log=a_log, dt_bias=dt_bias, scale=rcp_ln2, chunk_size=ctx.chunk_size,
            lower_bound=ctx.lower_bound, **varlen,
        )
        w, u, query_gated, key_gated = ops.recompute_w_u_fwd(
            q=query, k=key, v=value, beta=beta, A=attention_kk, gk=gate, **varlen,
        )
        states, value_new, _ = ops.chunk_gated_delta_rule_fwd_h(
            k=key_gated, w=w, u=u, gk=gate, initial_state=kernel_initial_state, output_final_state=False,
            chunk_size=ctx.chunk_size, **recurrent_varlen,
        )
        grad_attention_qk, grad_value_local = ops.chunk_kda_bwd_dav(
            q=query, k=key, v=value_new, do=grad_output, A=attention_qk, scale=ctx.scale,
            chunk_size=ctx.chunk_size, **varlen,
        )
        grad_final_state, send_handle, send_state_gradient = _exchange_backward(
            ctx, query_gated, key_gated, w, gate, grad_output, grad_value_local,
            (query.shape[0], value.shape[2], query.shape[-1], value.shape[-1]),
            state_cache, grad_final_state, recv_handle)
        kernel_grad_final = grad_final_state if sequence_info is None else sequence_info.last_state(grad_final_state)
        grad_states, _, grad_value = ops.chunk_gated_delta_rule_bwd_dhu(
            q=query_gated, k=key_gated, w=w, gk=gate, h0=kernel_initial_state, dht=kernel_grad_final, do=grad_output,
            dv=grad_value_local, scale=ctx.scale, chunk_size=ctx.chunk_size, **recurrent_varlen,
        )
        # These recomputed tensors have no consumers after dhu. Dropping local
787
788
789
790
791
792
793
794
795
796
            dv=grad_value_local, scale=ctx.scale, chunk_size=ctx.chunk_size, **recurrent_varlen,
        )
        # These recomputed tensors have no consumers after dhu. Dropping local
        # references lets the allocator reuse their storage on this stream.
        del query_gated, key_gated, w, u, grad_value_local, _
        (
            grad_query, grad_key, grad_value, grad_beta, grad_gate, grad_attention_kk,
        ) = ops.chunk_kda_bwd_wy_dqkg_fused(
            q=query, k=key, v=value, v_new=value_new, g=gate, beta=beta, A=attention_kk, h=states, do=grad_output,
            dh=grad_states, dv=grad_value, scale=ctx.scale, chunk_size=ctx.chunk_size,
796
797
798
799
800
801
802
803
804
805
            dh=grad_states, dv=grad_value, scale=ctx.scale, chunk_size=ctx.chunk_size,
            **varlen,
        )
        # Release recomputed states before intra backward allocates its outputs.
        del states, grad_states, value_new
        grad_query, grad_key, grad_beta, grad_gate = ops.chunk_kda_bwd_intra(
            q=query, k=key, g=gate, beta=beta, dAqk=grad_attention_qk, dAkk=grad_attention_kk, dq=grad_query,
            dk=grad_key, db=grad_beta, dg=grad_gate, chunk_size=ctx.chunk_size, safe_gate=ctx.safe_gate,
            **varlen,
        )
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
            dk=grad_key, db=grad_beta, dg=grad_gate, chunk_size=ctx.chunk_size, safe_gate=ctx.safe_gate,
            **varlen,
        )

        num_query_heads = query.shape[2]
        num_value_heads = value.shape[2]
        if num_value_heads > num_query_heads:
            groups = num_value_heads // num_query_heads
            grad_query = grad_query.view(*grad_query.shape[:2], num_query_heads, groups, grad_query.shape[-1]).sum(
                dim=3,
            )
            grad_key = grad_key.view(*grad_key.shape[:2], num_query_heads, groups, grad_key.shape[-1]).sum(dim=3)

        grad_gate = ops.chunk_local_cumsum(grad_gate, chunk_size=ctx.chunk_size, reverse=True, **varlen)
        grad_gate, grad_a_log, grad_dt_bias = ops.kda_gate_bwd(
            g=gate_raw, A_log=a_log, dt_bias=dt_bias, dyg=grad_gate, lower_bound=ctx.lower_bound,
        )
        grad_beta = ops.fused_beta_sigmoid_bwd(beta_raw, grad_beta)
        grad_query = ops.l2norm_bwd(query, query_rstd, grad_query)
        grad_key = ops.l2norm_bwd(key, key_rstd, grad_key)
        if send_handle is not None:
            send_handle.wait()
        del send_state_gradient

        return (
            grad_query, grad_key, grad_value, grad_gate, grad_beta, grad_a_log, grad_dt_bias, None, None, None,
            None, None, None, None, None, None, None, None,
        )
878
879
880
881
882
883
884
885
886

    Returns:
        Output tokens in the local sequence layout.
    """
    _validate_state_cp_inputs(
        query,
        key,
        value,
        gate,
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
        lower_bound=lower_bound,
        cp_rank=cp_rank,
        cp_size=cp_size,
    )
    if sequence_info is not None:
        if query.shape[0] != 1:
            raise ValueError("Packed state CP requires batch dimension one.")
        resolve_packed_sequence({"packed_sequence_info": sequence_info}, query.shape[1],
                                cp_rank=cp_rank, cp_size=cp_size)
    effective_scale = query.shape[-1] ** -0.5 if scale is None else float(scale)
    return _KDAStateCPFunction.apply(
        query,
        key,
        value,
        gate,
hyper_parallel/components/modules/attention/kimi_delta_attention/cp_recursive_doubling.py
32
33
34
35
36
37
38
39
40

    def __init__(self, group: Any, rank: int, ranks: tuple[int, ...]) -> None:
        """Resolve ordered peers and the process group's protocol device."""
        if not ranks or len(set(ranks)) != len(ranks) or not 0 <= rank < len(ranks):
            raise ValueError("RD requires unique global peers and a valid local rank")
        if tuple(dist.get_process_group_ranks(group)) != ranks:
            raise ValueError("RD mesh sequence order must match its communication group order")
        self.group, self.rank, self.size, self.peers = group, rank, len(ranks), ranks
        if dist.get_backend(group) != "hccl":
40
41
42
43
44
45
46
47
48
49
        if dist.get_backend(group) != "hccl":
            raise ValueError("KDA recursive doubling requires an HCCL process group")
        # Receive-only TND ranks have no local summary to infer a device from.
        # Load the optional extension here and bind buffers to the caller's NPU.
        torch_npu = importlib.import_module("torch_npu")
        self.device = torch.device("npu", torch_npu.npu.current_device())

    def __call__(
        self, payload: torch.Tensor | None, destination: int | None, source: int | None,
        receive_shape: tuple[int, ...] | None = None,
78
79
80
81
82
83
84
85
86
                raise ValueError('RD send requires a payload')
            if source is not None and receive_shape is None:
                raise ValueError('RD receive without a payload requires a shape')
        elif payload.device != self.device or not payload.is_contiguous():
            raise ValueError('RD payload must be contiguous on the protocol device')
        if any(peer is not None and not 0 <= peer < self.size for peer in (source, destination)):
            raise ValueError('RD peer is outside the process group')
        output = None
        if source is not None:
194
195
196
197
198
199
200
201
202
        """Reuse local bounds or locate another rank for an audit query."""
        if rank == self.local_rank and self._local_interval is not None:
            return self._local_interval
        if not 0 <= rank < self.size:
            raise ValueError("RD execution-plan rank is outside the state process group")
        return _rank_interval(self.offsets, self.local_length, rank)

    def peers(self, stage: int, rank: int) -> tuple[int | None, int | None]:
        """Return forward destination/source, both in process-group order.
204
205
206
207
208
209
210
211
        Args:
            stage: Index of the planned doubling round.
            rank: Rank index in sequence order.
        """
        return self._interval(rank).peers(rank, self.distances[stage])

    def shift_peers(self, rank: int) -> tuple[int | None, int | None]:
        """Return the tail's consumer and the head's producer independently.
249
250
251
252
253
254
255
256
257
    """Share document validation across rank-specific plans with bounded storage."""
    if (size < 1 or local_length < 1 or len(offsets) < 2 or offsets[0] != 0
            or offsets[-1] != size * local_length
            or any(left >= right for left, right in zip(offsets, offsets[1:]))):
        raise ValueError("RD reset planning requires ordered documents covering equal state-rank intervals")


@lru_cache(maxsize=32)
def _reverse_documents(offsets: tuple[int, ...] | PackedDocumentInfo) -> PackedDocumentInfo:
255
256
257
258
259
260
261
262
263
264

@lru_cache(maxsize=32)
def _reverse_documents(offsets: tuple[int, ...] | PackedDocumentInfo) -> PackedDocumentInfo:
    """Cache the reversed immutable snapshot across layers of the same batch."""
    values = offsets.offsets if isinstance(offsets, PackedDocumentInfo) else offsets
    return PackedDocumentInfo(tuple(values[-1] - value for value in reversed(values)))


@lru_cache(maxsize=32)
def build_reset_plan(
280
281
282
283
284
285
286
287
288
289
290
291
292
293
        An immutable CPU plan reusable across layers with identical metadata.
        Omitting rank retains only metadata for subsequent diagnostic queries.
    """
    if rank is not None and not 0 <= rank < size:
        raise ValueError("RD execution-plan rank is outside the state process group")
    if reverse:
        if not isinstance(offsets, PackedDocumentInfo):
            _validate_intervals(offsets, local_length, size)
        offsets = _reverse_documents(offsets)
        rank = None if rank is None else size - rank - 1
    if isinstance(offsets, PackedDocumentInfo):
        offsets = offsets.offsets
        if size < 1 or local_length < 1 or offsets[-1] != size * local_length:
            raise ValueError("RD reset planning requires ordered documents covering equal state-rank intervals")
hyper_parallel/components/modules/attention/kimi_delta_attention/cp_state_ascendc.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

@lru_cache(maxsize=1)
def _load_state_ops():
    """Check every native stage before entering the first state collective."""
    ops = load_kda_native_ops()
    required = (
        "pre_process_fwd_kernel_merged", "pre_process_bwd_kernel_merged",
        "merge_fwd_bwd_kernel",
    )
    missing = [name for name in required if not callable(getattr(ops, name, None))]
    if missing:
        raise RuntimeError(f"Native KDA state CP requires these fla-npu APIs: {', '.join(missing)}.")
    return ops


def _native_ag_intervals(info, tokens, rank, size):
    """Return tail/head windows and document-bounded exclusive scan lengths."""
    if info is None:
        return (0, tokens), (0, tokens), rank, size - rank - 1
    first_rank = (info.start - info.preceding_sample_tokens) // tokens
    last_rank = (info.global_offsets[bisect_left(info.global_offsets, info.end)] - 1) // tokens
    return ((info.tail.start, info.tail.stop), (info.head.start, info.head.stop),
            rank - first_rank if info.continues_previous else 0,
            last_rank - rank if info.continues_next else 0)

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    """

    def __init__(self, mesh: Any, executor: Any, info: Any, local_length: int, heads: int) -> None:
        """Copy communication metadata and retain only this call's sequence plan."""
        self.executor, self.info, self.heads = executor, info, heads
        self.rank = mesh.get_local_rank()
        self.size = mesh.size()
        self.ranks = tuple(mesh.rank_list)
        self.group = mesh.get_group()
        self.width = getattr(executor, "width", self.size) if executor is not None else 1
        self.block, self.local = divmod(self.rank, self.width)
        self.owner = self.block * self.width + self.width - 1
        self.is_rd = getattr(executor, "protocol", None) == "recursive_doubling"
        self.plans = (tuple(executor.directional_plan(info, local_length, reverse=reverse) for reverse in (False, True))
                      if self.is_rd else ())

    def peer(self, forward: bool, receiving: bool) -> int | None:
        """Return a chronological peer, pruning disconnected ordinary P2P edges.
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        Args:
            forward: Whether to use forward state traffic rather than backward gradient traffic.
            receiving: Whether to select the incoming peer rather than the outgoing peer.
        """
        direction = 1 if forward else -1
        peer = self.owner + (-direction if receiving else direction) * self.width
        if not 0 <= peer < self.size:
            return None
        if self.width == 1 and self.info is not None:
            needs_previous = forward == receiving
            connected = self.info.continues_previous if needs_previous else self.info.continues_next
            if not connected:
                return None
        return peer

    def needs_summary(self, forward: bool) -> bool:
        """Avoid producing a summary without an exit consumer.
100
101
102
103
104
105
106
107
108
109
110

        Args:
            forward: Select the forward S/M or backward G/N direction.
        """
        if self.is_rd:
            plan = self.plans[not forward]
            return plan.shift_peers(plan.local_rank)[0] is not None
        return self.width > 1 or self.peer(forward, receiving=False) is not None

    def receive(self, reference: torch.Tensor, forward: bool) -> tuple[torch.Tensor | None, Any]:
        """Post reception before native prepare, independently of summary production.
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
        Args:
            reference: Head-major input supplying the head count and device.
            forward: Select the chronological communication direction.
        """
        if self.is_rd or self.width == self.size:
            return None, None
        incoming = reference.new_zeros((1, reference.shape[1], 128, 128), dtype=torch.float32)
        peer = self.peer(forward, receiving=True)
        handle = None
        if self.rank == self.owner and peer is not None:
            handle = dist.irecv(incoming, src=self.ranks[peer], group=self.group)
        return incoming, handle

    @staticmethod
    def apply(packed: torch.Tensor, incoming: torch.Tensor | None) -> torch.Tensor:
        """Apply forward M or native backward N directly, without transposing N.
129
130
131
132
133
134
135
136
137
        Args:
            packed: Packed state and transition tensors for the scan.
            incoming: State entering this rank or group.
        """
        return apply_kda_state_summary(packed[..., :128], packed[..., 128:], incoming)

    def exchange(self, ops: Any, packed: torch.Tensor | None,
                 reception: tuple[torch.Tensor | None, Any], forward: bool,
                 count: int) -> tuple[torch.Tensor, Any, torch.Tensor | None]:
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
            reception: Previously posted receive buffer and handle.
            forward: Select the chronological communication direction.
            count: Number of maps in the relevant AllGather prefix or suffix.
        """
        if self.is_rd:
            state_shape = (1, self.heads, 128, 128)
            maps = None if packed is None else packed.reshape(1, self.heads, 128, 256)
            result = self.executor.scan_affine(maps, self.plans[not forward], state_shape, reverse=not forward)
            return result, None, None
        if self.width == self.size:
            maps = self.executor.gather_packed(packed.reshape(1, *packed.shape[-3:]))
            incoming = maps.new_zeros((maps.shape[1], 128, 128))
            if count:
                ops.merge_fwd_bwd_kernel(incoming, maps, count, self.rank, forward=forward)
            return incoming.unsqueeze(0), None, None
        incoming, recv_handle = reception
        if self.width > 1:
            return self._grouped_exchange(packed, incoming, recv_handle, forward)
        transfer = self.info is None or self.info.num_sequences == 1
        if recv_handle is not None and transfer:
            recv_handle.wait()
            recv_handle = None
        send_handle, outgoing = None, None
        peer = self.peer(forward, receiving=False)
        if peer is not None:
            outgoing = self.apply(packed, incoming if transfer else None).contiguous()
            send_handle = dist.isend(outgoing, dst=self.ranks[peer], group=self.group)
        # A reset permits sending the independent tail/head before this wait,
        # but local h/dhu still consumes the received first/last fragment state.
        if recv_handle is not None:
            recv_handle.wait()
        return incoming, send_handle, outgoing

    def _grouped_exchange(self, packed, incoming, recv_handle, forward):
        """Gather native maps within a group and relay only its exit state."""
        if self.info is not None:
            if not self.info.transfer_active or not self.info.continues_next:
                packed[..., 128:].zero_()
            connected = self.info.continues_next if forward else self.info.continues_previous
            if not connected:
                packed[..., :128].zero_()
        maps = packed.new_empty((self.width, *packed.shape[-3:]))
        dist.all_gather_into_tensor(maps, packed.reshape(1, *packed.shape[-3:]), group=self.executor.intra)
        send_handle, outgoing, result = None, None, None
        indices = range(self.width) if forward else range(self.width - 1, -1, -1)
        prefix_count = self.local if forward else self.width - self.local - 1
        if self.rank == self.owner:
            if recv_handle is not None:
                recv_handle.wait()
            peer = self.peer(forward, receiving=False)
            if peer is not None:
                outgoing, result = self._scan(maps, incoming, indices, prefix_count)
                send_handle = dist.isend(outgoing, dst=self.ranks[peer], group=self.group)
        if self.peer(forward, receiving=True) is not None:
            dist.broadcast(incoming, src=self.ranks[self.owner], group=self.executor.intra)
        if result is None:
            local_indices = range(self.local) if forward else range(self.width - 1, self.local, -1)
            result, _ = self._scan(maps, incoming, local_indices)
        return result, send_handle, outgoing

    @staticmethod
    def _scan(maps, incoming, indices, prefix_count=None):
        """Keep native M/N orientation while applying a nonzero group entry."""
        state = incoming
        prefix = incoming if prefix_count == 0 else None
        for step, index in enumerate(indices, start=1):
            state = _NativeStateExchange.apply(maps[index:index + 1], state)
            if step == prefix_count:
                prefix = state
        return state, prefix


def _exchange_native_gradient(ctx, ops, inputs, reception):
    """Own G/N production, reset injection and the stock dHT dtype boundary."""
    if ctx.exchange is None:
        return None, None, None
    gk, qg, kg, weights, grad, dv_local_head = inputs
    maps = None
    if ctx.exchange.needs_summary(False):
        # Only the stock G/N ABI rounds gk; local dhu/finalize retain FP32.
        maps = ops.pre_process_bwd_kernel_merged(
            qg, kg, weights, grad, dv_local_head, ctx.scale, 64,
            gk=gk.to(qg.dtype), cu_seqlens=ctx.head)
    terminal, send_handle, outgoing = ctx.exchange.exchange(ops, maps, reception, False, ctx.suffix)
    if ctx.exchange.info is not None:
        terminal = ctx.exchange.info.last_state(terminal)
    # Communication and summary apply retain FP32; only stock dhu requires BF16.
    terminal = None if terminal is None else terminal.to(qg.dtype)
    return terminal, send_handle, outgoing


class _AscendCKDAState(torch.autograd.Function):
    """Share native local stages; state protocols optionally inject H and D."""
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
            lower_bound: Safe-gate lower bound.
            metadata: Native packed offsets and chunk indices.
            exchange: Optional state protocol for this invocation.
        """
        ops = _load_state_ops()
        inputs = (query, key, value, gate, beta, a_log, dt_bias)
        reception = None if exchange is None else exchange.receive(query, True)
        prepared = prepare_kda_native(inputs, scale, lower_bound, metadata)
        initial = send_handle = outgoing = head = suffix = None
        if exchange is not None:
            tail, head, prefix, suffix = _native_ag_intervals(
                exchange.info, query.shape[2], exchange.rank, exchange.size)
            maps = None
            if exchange.needs_summary(True):
                maps = ops.pre_process_fwd_kernel_merged(
                    prepared.kg, prepared.w, prepared.u, gk=prepared.gk, cu_seqlens=tail)
            initial, send_handle, outgoing = exchange.exchange(ops, maps, reception, True, prefix)
            del maps, reception
            if exchange.info is not None:
                initial = exchange.info.first_state(initial)
        output = finish_kda_native_forward(ctx, inputs, prepared, initial, scale, lower_bound, metadata)
        if send_handle is not None:
            send_handle.wait()
        del outgoing
        ctx.exchange, ctx.head, ctx.suffix = exchange, head, suffix
        return output

    @staticmethod
    @once_differentiable
    def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        Args:
            ctx: Forward-owned activations and communication metadata.
            grad_output: Sequence-major output gradient.
        """
        ops = _load_state_ops()
        # Share one unpack across phases, including checkpoint recomputation.
        saved = ctx.saved_tensors
        gk, weights, qg, kg, query = saved[4], saved[7], saved[9], saved[10], saved[12]
        reception = ctx.exchange.receive(query, False)
        grad, d_aqk, dv_local_head, dq_raw = prepare_kda_native_backward(ctx, saved, grad_output)
        terminal, send_handle, outgoing = _exchange_native_gradient(
            ctx, ops, (gk, qg, kg, weights, grad, dv_local_head), reception)
        del reception
        gradients = finish_kda_native_backward(ctx, saved, grad, d_aqk, dv_local_head, dq_raw, terminal)
        if send_handle is not None:
            send_handle.wait()
        del outgoing
        return (*gradients, None, None, None, None)


def ascendc_state_kda(
    query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
        backward summary gk and local dhu dHT are converted to model dtype.
        Prepared gates, communicated states and summary apply remain FP32.
        These ABI conversions introduce rounding relative to FP32-input kernels.
    """
    if query.device.type != "npu" or query.dtype != torch.bfloat16:
        raise ValueError("Native KDA state CP requires BF16 NPU inputs.")
    if query.ndim != 4 or query.shape[0] != 1 or query.shape[-1] != 128:
        raise ValueError("Native KDA state CP requires [1,T,H,128] inputs.")
    if any(tensor.shape != query.shape for tensor in (key, value, gate)) or beta.shape != query.shape[:-1]:
        raise ValueError("Native KDA state CP requires matching Q/K/V/gate heads and beta [1,T,H].")
    metadata = local_chunk_metadata(None if sequence_info is None else sequence_info.local_offsets, query.shape[1])
    scale = query.shape[-1] ** -0.5 if scale is None else float(scale)
    tokens = tuple(tensor.transpose(1, 2).contiguous() for tensor in (query, key, value))
    exchange = _NativeStateExchange(cp_mesh, state_cp, sequence_info, query.shape[1], query.shape[2])
    return _AscendCKDAState.apply(
        *tokens, gate.contiguous(), beta.contiguous(), a_log.reshape(-1).clone(),
        dt_bias.reshape(-1, query.shape[-1]).clone(), scale, lower_bound, metadata, exchange)
hyper_parallel/components/modules/attention/kimi_delta_attention/kimi_delta_attention.py
82
83
84
85
86
87
88
89
90
                 chunk_size: int = 64, input_layout: str = "BSH") -> None:
        """Construct local parameters or adopt source weights without renaming them."""
        super().__init__()
        if (config is None) == (module is None):
            raise ValueError("KDA requires exactly one of config or module")
        self.config = config if module is None else getattr(module, "config", None)
        self.backend = backend
        self.conv_backend = validate_conv_backend(backend if conv_backend is None else conv_backend)
        self.chunk_size = chunk_size
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        if self.use_short_conv:
            for name in ("q_conv1d", "k_conv1d", "v_conv1d"):
                validate_causal_convolution(getattr(self, name), require_activation=True)
        if self.backend not in ("eager", "triton", "ascendc"):
            raise ValueError("KDA backend must be eager, triton or ascendc")
        if self.backend != "eager" and (self.head_k_dim != 128 or self.head_v_dim != 128 or self.chunk_size != 64):
            raise ValueError("Fused KDA requires K=V=128 and chunk_size=64")
        if getattr(self, "allow_neg_eigval", False):
            raise NotImplementedError("KDA family does not support allow_neg_eigval=True")
        if not self.safe_gate or self.lower_bound is None or self.lower_bound >= 0:
            raise ValueError("KDA family requires its lower-bounded gate")

    def __deepcopy__(self, memo: dict) -> nn.Module:
        """Retain pre-binding model-copy behavior without copying process groups."""
        return copy_unbound_linear_attention(self, memo)
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        self.use_full_rank_gate = getattr(config, "use_full_rank_gate", True)
        self.layer_idx = getattr(config, "layer_idx", 0)
        rms_norm_eps = getattr(config, "rms_norm_eps", 1e-6)
        if self.hidden_size is None or self.hidden_size <= 0 or self.num_heads <= 0:
            raise ValueError("hidden_size and num_heads must be positive.")
        if self.num_v_heads is None:
            self.num_v_heads = self.num_heads
        if self.num_v_heads <= 0 or self.num_v_heads % self.num_heads:
            raise ValueError("num_v_heads must be positive and divisible by num_heads.")
        if self.head_k_dim <= 0 or self.head_v_dim <= 0:
            raise ValueError("KDA head dimensions must be positive.")
        if self.conv_kernel_size <= 0 or self.chunk_size <= 0:
            raise ValueError("conv_kernel_size and chunk_size must be positive.")
        if self.gate_lower_bound >= 0:
            raise ValueError("gate_lower_bound must be negative.")

        self.head_dim = self.head_v_dim
        self.key_dim = self.num_heads * self.head_k_dim
        self.value_dim = self.num_v_heads * self.head_v_dim
170
171
172
173
174
175
176
177
178
        self.b_proj = nn.Linear(self.hidden_size, self.num_v_heads, bias=False)
        if self.use_full_rank_gate:
            self.g_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
        else:
            self.g_a_proj = nn.Linear(self.hidden_size, self.head_v_dim, bias=False)
            self.g_b_proj = nn.Linear(self.head_v_dim, self.value_dim, bias=False)
        self.o_norm = KimiRMSNormGated(self.head_v_dim, eps=rms_norm_eps)
        self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)

182
183
184
185
186
187
188
189
190
191
192
193
194
        required = ("q_proj", "k_proj", "v_proj", "b_proj", "o_norm", "o_proj", "A_log", "dt_bias",
                    "num_heads", "head_k_dim")
        missing = [name for name in required if not hasattr(module, name)]
        if missing:
            raise TypeError(f"KDA source is missing {missing}")
        if not (hasattr(module, "f_proj") or all(hasattr(module, name) for name in ("f_a_proj", "f_b_proj"))):
            raise TypeError("KDA source requires f_proj or f_a_proj/f_b_proj")
        if not (hasattr(module, "g_proj") or all(hasattr(module, name) for name in ("g_a_proj", "g_b_proj"))):
            raise TypeError("KDA source requires g_proj or g_a_proj/g_b_proj")
        owners = ("q_proj", "k_proj", "v_proj", "q_conv1d", "k_conv1d", "v_conv1d", "A_log", "dt_bias",
                  "f_proj", "f_a_proj", "f_b_proj", "b_proj", "g_proj", "g_a_proj", "g_b_proj", "o_norm", "o_proj")
        adopt_source_parameters(self, module, owners)
        self.num_heads = self.num_k_heads = module.num_heads
196
197
198
199
200
201
202
203
204
        self.head_k_dim = module.head_k_dim
        self.head_v_dim = getattr(module, "head_v_dim", getattr(module, "head_dim", None))
        self.head_dim = self.head_v_dim
        if self.num_v_heads % self.num_heads:
            raise ValueError("KDA value heads must be divisible by query heads")
        self.key_dim = self.num_heads * self.head_k_dim
        self.value_dim = self.num_v_heads * self.head_v_dim
        self.hidden_size = self.q_proj.in_features
        self.layer_idx = getattr(module, "layer_idx", None)
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235

        Returns:
            An empty conversion list; source Parameter objects are adopted directly.
        """
        return []

    def reset_parameters(self) -> None:
        """Reset native/meta construction, without resetting adopted source weights."""
        if not self._config_initialization:
            return
        for child in self.children():
            if isinstance(child, (nn.Linear, nn.Conv1d)):
                child.reset_parameters()
        nn.init.uniform_(self.A_log, 1, 16)
        with torch.no_grad():
            self.A_log.log_()
        nn.init.zeros_(self.dt_bias)
        nn.init.ones_(self.o_norm.weight)

    def project_inputs(self, hidden_states: torch.Tensor) -> tuple:
        """Project Q/K/V in the source order, before convolution or head exchange.
269
270
271
272
273
274
275
276
277
            query, key, value = (run_causal_short_conv(tensor, conv, sequence_info=info, backend=self.conv_backend)
                                 for tensor, conv in zip((query, key, value),
                                                         (self.q_conv1d, self.k_conv1d, self.v_conv1d)))
        else:
            query, key, value = (F.silu(tensor) for tensor in (query, key, value))
        return query, key, value

    def shape_inputs(self, operands: tuple, degree: int = 1) -> tuple:
        """Expose head axes without changing raw gate or beta semantics.
353
354
355
356
357
358
359
360
361
362
363
364
365
            use_cache: Inference-cache request; unsupported by this training entry.
            output_attentions: Source-model attention-weight request; KDA returns no attention matrix.
        """
        if use_cache or past_key_values is not None or kwargs.get("cache_params") is not None:
            raise NotImplementedError("KDA family supports training without recurrent cache")
        if output_attentions:
            raise NotImplementedError("KDA does not materialize attention weights")
        if attention_mask is not None and not bool(attention_mask.bool().all().item()):
            raise NotImplementedError("Padded KDA batches are not implemented")
        hidden_states, info, is_flat_input = self.prepare_input(hidden_states, kwargs)
        output, gate = self.execute_attention_pipeline(hidden_states, info)
        del hidden_states
        output = self.project_output(output, gate)
hyper_parallel/components/modules/attention/kimi_delta_attention/kimi_delta_attention_family.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def _validate_kda_state_protocol(options: Any, cp: int, degree: int, backend: str) -> None:
    """Keep state protocol qualifications separate from layout validation."""
    protocol = options.get("state_cp_method", "p2p")
    if protocol not in ("p2p", "allgather", "grouped_allgather_p2p", "recursive_doubling"):
        raise ValueError("Unknown KDA state_cp_method")
    group = options.get("allgather_group_size", 1)
    if (not isinstance(group, int) or isinstance(group, bool)) or group < 1 or (cp > 1 and (cp // degree) % group):
        raise ValueError("allgather_group_size must divide state CP size")
    if group != 1 and protocol != "grouped_allgather_p2p":
        raise ValueError("allgather_group_size is only valid for grouped_allgather_p2p")
    if cp > degree and backend == "eager":
        raise NotImplementedError("Eager KDA supports local/pure Ulysses only; state CP requires Triton or Ascend C")


def validate_kda_family(*, config: Any, module: nn.Module | None, context: Any, member: Any) -> None:
    """Check this family's supported algorithms before constructing parameters or groups."""
60
61
62
63
64
65
66
67
68
    kh = getattr(source, "num_heads", None)
    vh = getattr(source, "num_v_heads", None) or kh
    head_degree = member.axis_sizes["tp"] * (degree if cp > 1 else 1)
    if kh is not None and (kh % head_degree or vh % head_degree):
        raise ValueError("TP times Ulysses degree must divide both query and value heads")
    _validate_kda_state_protocol(member.arguments, cp, degree, backend)


def kda_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
146
147
148
149
150
151
152
153
154
        layer_idx: Source layer index retained in direct construction.
    """
    if hidden_size is not None:
        if config is not None or module is not None:
            raise ValueError("hidden_size construction cannot be combined with config or module")
        config = SimpleNamespace(hidden_size=hidden_size, num_heads=num_heads, num_v_heads=num_v_heads,
                                 head_k_dim=head_k_dim, head_v_dim=head_v_dim, conv_kernel_size=conv_kernel_size,
                                 gate_lower_bound=gate_lower_bound, use_full_rank_gate=use_full_rank_gate,
                                 rms_norm_eps=rms_norm_eps, layer_idx=layer_idx)
hyper_parallel/components/modules/attention/linear_attention_utils/cp_convolution.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        cp_size: Number of ranks in the CP mesh.
        sequence_info: Immutable document metadata for this local token interval.
        backend: Explicit local operator implementation to dispatch.
    """
    halo_widths = {
        (conv.kernel_size[0] - 1) * conv.dilation[0] for conv in convolutions
    }
    if len(halo_widths) != 1:
        raise ValueError("Linear attention CP requires Q/K/V ShortConv halo widths to match.")
    halo_width = halo_widths.pop()
    if halo_width == 0 or cp_size == 1:
        return tuple(
            run_causal_short_conv(tensor, convolution, sequence_info=sequence_info, backend=backend)
            for tensor, convolution in zip(projected, convolutions)
        )
    if projected[0].shape[1] < halo_width:
        raise ValueError(
            "Linear attention CP ShortConv requires local_seq_len >= halo width, got "
            f"{projected[0].shape[1]} < {halo_width}."
        )

    channel_sizes = [tensor.shape[-1] for tensor in projected]
    packed_tail = torch.cat(
        [tensor[:, -halo_width:, :] for tensor in projected],
        dim=-1,
    ).contiguous()
    packed_halo = _exchange_previous_rank_halo(
        packed_tail,
        cp_mesh,
        cp_rank,
        cp_size,
72
73
74
75
76
77
78
79
80
        cp_mesh,
        cp_rank,
        cp_size,
    )
    halos = torch.split(packed_halo, channel_sizes, dim=-1)
    return tuple(
        run_causal_short_conv(tensor, convolution, halo, sequence_info=sequence_info, backend=backend)
        for tensor, halo, convolution in zip(projected, halos, convolutions)
    )
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
        cp_mesh: Sequence-ordered CP device mesh.
        cp_rank: Rank index within the CP mesh.
        cp_size: Number of ranks in the CP mesh.
    """
    if cp_size == 1:
        return torch.zeros_like(tail)

    cp_group = cp_mesh.get_group()
    group_ranks = tuple(int(rank) for rank in dist.get_process_group_ranks(cp_group))
    rank_list = tuple(int(rank) for rank in cp_mesh.rank_list)
    rank_to_group_index = {rank: index for index, rank in enumerate(group_ranks)}
    halo_width = tail.shape[1]

    input_splits = [0] * cp_size
    exchange_input = tail.permute(1, 0, 2).contiguous()
    if cp_rank < cp_size - 1:
        input_splits[rank_to_group_index[rank_list[cp_rank + 1]]] = halo_width
    else:
        exchange_input = exchange_input[:0]

    output_splits = [0] * cp_size
    if cp_rank > 0:
        output_splits[rank_to_group_index[rank_list[cp_rank - 1]]] = halo_width

    exchange_output = communication.differentiable_all_to_all_single(
        exchange_input,
        input_splits,
        output_splits,
        group=cp_group,
119
120
121
122
123
124
125
        input_splits,
        output_splits,
        group=cp_group,
    )
    if cp_rank == 0:
        return torch.zeros_like(tail) + exchange_output.sum().to(tail.dtype) * 0
    return exchange_output.permute(1, 0, 2).contiguous()
hyper_parallel/components/modules/attention/linear_attention_utils/layer_adapter.py
37
38
39
40
41
42
43
44
45
        names: Algorithm-owned top-level parameter and submodule names.
    """
    unknown = {name.split('.')[0] for name, _ in source.named_parameters()} - set(names)
    if unknown:
        raise ValueError(f"Unsupported linear-attention parameter owners: {sorted(unknown)}")
    # Raw registries preserve aliases, None slots and buffer persistence that
    # named_parameters()/named_buffers() cannot expose together.
    for name, parameter in source._parameters.items():  # pylint: disable=protected-access
        if name in names:
48
49
50
51
52
53
54
55
56
        # Parameterless source helpers also belong to the registered-module contract.
        # Unknown parameter owners were rejected above, so preserving them is safe.
        target.add_module(name, child)
    for name, buffer in source._buffers.items():  # pylint: disable=protected-access
        persistent = name not in source._non_persistent_buffers_set  # pylint: disable=protected-access
        target.register_buffer(name, buffer, persistent=persistent)
    # Do not call train() recursively: source children may intentionally differ.
    target.training = source.training

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        cp_rank: Logical sequence rank, independent of global rank numbering.
        cp_size: Number of equal contiguous token shards.
    """
    if isinstance(hidden_states, DTensor):
        hidden_states = hidden_states.to_local()
    is_flat_input = hidden_states.ndim == 2
    if is_flat_input:
        hidden_states = hidden_states.unsqueeze(0)
    if hidden_states.ndim != 3:
        raise ValueError("Linear attention expects [B,T,C] or [T,C] inputs")
    info = resolve_packed_sequence(options, hidden_states.shape[1], cp_rank=cp_rank, cp_size=cp_size)
    if info is not None and hidden_states.shape[0] != 1:
        raise ValueError("Packed linear attention requires batch dimension one")
    return hidden_states, info, is_flat_input


def copy_unbound_linear_attention(module: nn.Module, memo: dict) -> nn.Module:
88
89
90
91
92
93
94
95
96
    Returns:
        An independent parameter copy with the same logical family request.
    """
    if getattr(module, "cp_context", None) is not None or getattr(module, "_hp_parallel_binding", None) is not None:
        raise RuntimeError("Copy linear-attention weights before binding communication resources")
    result = type(module).__new__(type(module))
    memo[id(module)] = result
    state = dict(module.__dict__)
    info = state.pop("_hp_family_build_info", None)
 96
 97
 98
 99
100
101
102
103
104
    info = state.pop("_hp_family_build_info", None)
    result.__dict__.update(deepcopy(state, memo))
    if info is not None:
        if info.layout is not None:
            raise RuntimeError("Copy linear-attention weights before applying a distributed layout")
        # Requests/selection contain only immutable execution options. Configuration
        # snapshots are independent so changing a copied config cannot affect promotion.
        # This copy retains the same private record owned by module_family.
        result._hp_family_build_info = replace(  # pylint: disable=protected-access
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        options: Explicit backend options or invocation document metadata.
    """
    backend = options.get("backend", "eager")
    if backend not in ("eager", "triton", "ascendc"):
        raise ValueError("backend must be eager, triton or ascendc")
    conv = options.get("conv_backend")
    if conv is not None and conv not in ("eager", "triton", "ascendc"):
        raise ValueError("conv_backend must be eager, triton or ascendc")
    chunk = options.get("chunk_size", 64)
    if (not isinstance(chunk, int) or isinstance(chunk, bool)) or chunk < 1 or (backend != "eager" and chunk != 64):
        raise ValueError("chunk_size must be positive; fused backends require 64")
    if options.get("input_layout", "BSH") not in ("BSH", "TH"):
        raise ValueError("input_layout must be BSH or TH; TH declares flat packed token axis 0")
    return backend
hyper_parallel/components/modules/attention/linear_attention_utils/parallel_layout.py
41
42
43
44
45
46
47
48
49
    for name, _ in module.named_parameters():
        params[name] = dict(placements)
        if context.axis_sizes["tp"] > 1:
            if name not in roles:
                raise ValueError(f"Linear-attention parameter {name!r} has no declared TP role")
            params[name]["tp"] = roles[name]
    tokens = dict(placements)
    token_axis = 0 if module.input_layout == "TH" else 1
    if context.axis_sizes["cp"] > 1:
67
68
69
70
71
72
73
74
75
76
77
        module: Existing source module or resolved family member.
        sharding: Proposed input, output and parameter placements.
        context: Logical parallel sizes or the resolved sharding context.
    """
    member = get_family_build_info(module).resolved
    expected = member.family.sharding(module=module, module_fqn="", member=member, context=context)
    validate_tp_boundary(sharding, expected, name=type(module).__name__,
                         sequence_dim=0 if module.input_layout == "TH" else 1)


def linear_attention_local_spec(*, module: nn.Module, member: Any) -> ParallelModuleSpec:
80
81
82
83
84
85
    Args:
        module: Existing source module or resolved family member.
        member: Resolved family member and its implementation arguments.
    """
    del module, member
    return ParallelModuleSpec("attention.linear.local", validate=validate_linear_attention_layout)
hyper_parallel/components/modules/attention/linear_attention_utils/sequence_layout.py
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
        tokens: Local packed token count.
        require_cpu: Reject device metadata when the native ABI requires host offsets.
    """
    if isinstance(cu_seqlens, torch.Tensor):
        if require_cpu and cu_seqlens.device.type != "cpu":
            raise ValueError("Native cu_seqlens must be a CPU integer tensor or sequence.")
        if cu_seqlens.ndim != 1 or cu_seqlens.dtype not in (torch.int32, torch.int64):
            raise ValueError("cu_seqlens must be a one-dimensional integer tensor.")
        cu_seqlens = cu_seqlens.detach().cpu().tolist()
    offsets = tuple(cu_seqlens)
    if (len(offsets) < 2 or offsets[0] != 0
            or any(not isinstance(value, int) or isinstance(value, bool) for value in offsets)
            or any(left >= right for left, right in zip(offsets, offsets[1:]))):
        raise ValueError("Packed sample offsets must be strictly increasing integers starting at zero.")
    if offsets[-1] != tokens:
        raise ValueError("Local cumulative offsets must end at the input token count.")
    return offsets
344
345
346
347
348
349
350
351
352
        initial_state: Optional incoming-state slot for each local sample fragment.
        output_final_state: Whether to return one outgoing state per local sample fragment.
    """
    if inputs[0].shape[0] != 1:
        raise ValueError("Packed eager requires batch dimension one.")
    offsets = local_sequence_offsets(cu_seqlens, inputs[0].shape[1])
    if initial_state is not None and initial_state.shape[0] != len(offsets) - 1:
        raise ValueError("Packed initial_state requires one slot per local sample fragment.")
    outputs, finals = [], []
376
377
378
379
380
381
382
383
384
385
386
387

    Returns:
        Local cu_seqlens and flattened chunk_indices, or an empty dense descriptor.
    """
    if cu_seqlens is None:
        return {}
    if chunk_size < 1:
        raise ValueError("chunk_size must be positive.")
    offsets = local_sequence_offsets(cu_seqlens, tokens, require_cpu=True)
    indices = tuple(value for seq, (begin, end) in enumerate(zip(offsets, offsets[1:]))
                    for chunk in range((end - begin + chunk_size - 1) // chunk_size) for value in (seq, chunk))
    return {"cu_seqlens": offsets, "chunk_indices": indices}
hyper_parallel/distributed/_builder/family_layout.py
142
143
144
145
146
147
148
149
        for axis in set(actual) | set(required):
            placement = actual.get(axis, Replicate())
            if axis == "tp" and field_name in ("in_src", "out_dst"):
                if placement not in (Replicate(), Shard(sequence_dim)):
                    raise ValueError(f"{name} TP token ports support Replicate or sequence Shard({sequence_dim})")
            elif placement != required.get(axis, Replicate()):
                raise ValueError(f"{name} {field_name} cannot change {axis} computation/ownership")

hyper_parallel/distributed/context_parallel/collectives.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
        device_mesh: Device mesh used for sequence/head redistribution.
        split_dim: Tensor dimension divided across the participating ranks.
        concat_dim: Tensor dimension assembled from the participating ranks.
    """
    split_count = device_mesh.size()
    if split_count == 1:
        return tensor

    original_shape = tuple(tensor.shape)
    if original_shape[split_dim] % split_count != 0:
        raise ValueError(
            f"Linear-attention all-to-all split dimension {split_dim} with size "
            f"{original_shape[split_dim]} must be divisible by cp_size "
            f"{split_count}."
        )
    split_size = original_shape[split_dim] // split_count
    final_shape = list(original_shape)
    final_shape[split_dim] = split_size
    final_shape[concat_dim] *= split_count

    reshape_dims = list(original_shape)
    reshape_dims[split_dim] = split_count
    reshape_dims.insert(split_dim + 1, split_size)
    permutation = list(range(len(reshape_dims)))
    permutation.remove(split_dim)
    permutation.insert(0, split_dim)
    all_to_all_input = tensor.reshape(reshape_dims).permute(permutation).contiguous()
    all_to_all_input = all_to_all_input.flatten(0, 1)

    split_length = all_to_all_input.shape[0] // split_count
    splits = [split_length] * split_count
    output = communication.differentiable_all_to_all_single(
        all_to_all_input,
        splits,
        splits,
        group=device_mesh.get_group(),
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
        splits,
        group=device_mesh.get_group(),
    )

    output_reshape = list(output.shape)
    output_reshape[0] = split_count
    output_reshape.insert(1, output.shape[0] // split_count)
    permutation = list(range(len(output_reshape)))
    rank_dimension = permutation.pop(0)
    permutation.insert(concat_dim, rank_dimension)
    output = output.reshape(output_reshape).permute(permutation).contiguous()

    output_shape = list(output.shape)
    output_shape[concat_dim] *= output_shape[concat_dim + 1]
    output_shape.pop(concat_dim + 1)
    return output.reshape(output_shape).view(final_shape)