Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/modules/gated_delta_net.py 63.3% 38,65-66,130,141,146,157-159,170-171,186-188,191-203,219-221,225-226,237,240,247,251
hyper_parallel/distributed/context_parallel/gated_delta_net.py 13.9% 50,60-62,66-67,80-81,99-101,106,114-117,120-121,125,130-132,145-146,148-152,154-157,159,161-163,165,171-173,184-189,191-192,197,203-204,213,218,247-250,252,257-264,266-269,273,275,279-286,288-290,308-311,314,322,324-330,332,336-338,340,347-348,350,357,363,365,381-386,398,400-407,410-411,422,428-429,444-448,452-455,469-474,478,483-484,493-495,518-519,530,532-535,537,546-549,551-553,560-562,567,569-571,573,594,599,604,622-626,631,633-636,643-645,647-650,655,657,665,674-675,677-678,688-695,700,705,710,720-721,723,735-737,747-750,755,760-762,764-767,772,778,789-790,811-813,827-828,838,840-843,846,874-876,878-881,886-891,893-895,897-899,901-905,907-911,918-920,922-925,927,929-932,935,937,958-962,966-977,981,987-989,993-996,1000-1001,1005-1007,1010,1018,1034-1035,1037-1040,1042-1047,1051-1053,1066,1076-1079,1096-1098,1102-1105,1110-1111,1113-1115,1121-1122,1124,1129,1133-1138,1140-1141,1150,1152,1157-1159,1161-1164,1166-1169,1171,1184-1191,1205-1209,1213-1222,1226,1232-1234,1238,1241,1245-1250,1253-1254,1257,1261,1267,1283-1285,1289-1290,1292-1293,1295-1297,1303-1304,1306-1307,1312-1314,1316-1317,1319-1322,1324-1326,1331-1332,1337,1348,1361-1367
hyper_parallel/components/modules/gated_delta_net.py
34
35
36
37
38
39
40
41
42
def _l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6) -> torch.Tensor:
    """L2-normalize along ``dim``."""
    # ``(x * x).sum`` (MulBackward) instead of ``x.pow(2).sum`` (PowBackward):
    # equal math, NPU yields ULP-different gradients across the two ops.
    return x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)


def torch_chunk_gated_delta_rule(
    query: torch.Tensor,
61
62
63
64
65
66
67
68
69
70
    beta:         ``(B, S, num_v_heads)``
    """
    initial_dtype = query.dtype
    if use_qk_l2norm_in_kernel:
        query = _l2norm(query, dim=-1, eps=1e-6)
        key = _l2norm(key, dim=-1, eps=1e-6)
    # (B, S, H, D) → (B, H, S, D), fp32
    query, key, value, beta, g = [
        x.transpose(1, 2).contiguous().to(torch.float32)
        for x in (query, key, value, beta, g)
126
127
128
129
130
131
132
133
134
            + (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
        )

    if not output_final_state:
        last_recurrent_state = None
    core_attn_out = core_attn_out.reshape(
        core_attn_out.shape[0], core_attn_out.shape[1], -1, core_attn_out.shape[-1],
    )
    core_attn_out = core_attn_out[:, :, :sequence_length]
137
138
139
140
141
142
143
144
145
146
147
148
149
150


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


def _is_triton_gdn_input_supported(
    query: torch.Tensor,
153
154
155
156
157
158
159
160
161
162
163
    g: Optional[torch.Tensor],
    beta: Optional[torch.Tensor],
) -> bool:
    """Check the fixed Qwen3.5 GDN contract validated by this backend."""
    if key is None or value is None or g is None or beta is None:
        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
166
167
168
169
170
171
172
173
174
        and query.shape[:3] == value.shape[:3] == g.shape == beta.shape
        and query.shape[-1] == value.shape[-1] == _TRITON_GDN_HEAD_DIM
        and query.shape[1] % _TRITON_GDN_CHUNK_SIZE == 0
    ):
        return False
    return all(
        tensor.device == query.device
        for tensor in (key, value, g, beta)
    )
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
    beta: Optional[torch.Tensor] = None,
    chunk_size: int = _TRITON_GDN_CHUNK_SIZE,
) -> bool:
    """Return whether the validated Triton-Ascend GDN backend is available."""
    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,
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
    use_qk_l2norm_in_kernel: bool = False,
    backend: str = "eager",
):
    """Dispatch GDN to an explicitly selected eager or Triton backend."""
    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":
        return torch_chunk_gated_delta_rule(
            query,
            key,
            value,
            g=g,
233
234
235
236
237
238
239
240
241
242
243
244
            initial_state=initial_state,
            output_final_state=output_final_state,
            use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
        )
    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, "
            "chunk_size=64, and sequence length divisible by 64."
243
244
245
246
247
248
249
250
251
252
253
254
255
            "q/k/v/beta=bf16, g=fp32, head_k_dim=head_v_dim=128, "
            "chunk_size=64, and sequence length divisible by 64."
        )

    from hyper_parallel.platform.torch.custom_ops.gdn.chunk_gated_delta_rule 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/distributed/context_parallel/gated_delta_net.py
46
47
48
49
50
51
52
53
54


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 _slice_local_cp(
    tensor: torch.Tensor,
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    cp_rank: int,
    cp_size: int,
) -> torch.Tensor:
    """Return this CP rank's contiguous slice along ``dim``."""
    dim_size = tensor.shape[dim]
    if dim_size % cp_size != 0:
        raise ValueError(
            f"linear attention CP expects dim size {dim_size} "
            f"to be divisible by cp_size {cp_size}."
        )
    chunk = dim_size // cp_size
    return tensor.narrow(dim, cp_rank * chunk, chunk)


def _slice_qkv_local_cp(
    tensor: torch.Tensor,
76
77
78
79
80
81
82
83
84
85
    cp_rank: int,
    cp_size: int,
) -> torch.Tensor:
    """Slice a fused ``[Q, K, V]`` tensor on the Q/K/V channel dimension."""
    q, k, v = torch.split(tensor, [key_dim, key_dim, value_dim], dim=dim)
    return torch.cat(
        (
            _slice_local_cp(q, dim, cp_rank, cp_size),
            _slice_local_cp(k, dim, cp_rank, cp_size),
            _slice_local_cp(v, dim, cp_rank, cp_size),
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
    activations as local sequence shards. If an upstream wrapper passes that
    shard as a DTensor, use its local tensor and continue with the same
    ``[B, S_local, H]`` boundary contract.
    """
    if isinstance(tensor, DTensor):
        return tensor.to_local()
    return tensor


def _kv_groups(module: nn.Module) -> int:
    """Return the Q/K replication factor used by the official HF GDN layer."""
    return int(module.num_v_heads // module.num_k_heads)


def _apply_local_padding_mask(
    hidden_states: torch.Tensor,
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
    hidden_states: torch.Tensor,
    attention_mask: Optional[torch.Tensor],
) -> torch.Tensor:
    """Apply the supported local 2-D padding mask without silent fallback."""
    if attention_mask is None:
        return hidden_states
    if attention_mask.ndim != 2:
        raise NotImplementedError(
            "Qwen3.5 GDN Context Parallel supports only a local 2-D padding mask."
        )
    if tuple(attention_mask.shape) != tuple(hidden_states.shape[:2]):
        raise ValueError(
            "Qwen3.5 GDN Context Parallel expects attention_mask shape "
            f"{tuple(hidden_states.shape[:2])}, got {tuple(attention_mask.shape)}."
        )
    return hidden_states * attention_mask[:, :, None].to(hidden_states.dtype)


def _validate_gdn_activation(module: nn.Module) -> None:
    """Reject model variants whose Conv activation is not implemented here."""
    activation = getattr(module, "activation", "silu")
    if activation not in ("silu", "swish"):
        raise NotImplementedError(
            "Qwen3.5 GDN Context Parallel currently supports only SiLU/Swish "
            f"Conv activation, got {activation!r}."
        )
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
    cp_rank: int,
    cp_size: int,
) -> torch.Tensor:
    """Send a convolution halo only to the next rank using differentiable A2AV."""
    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 = platform.differentiable_all_to_all_single(
        exchange_input,
        input_splits,
        output_splits,
        group=cp_group,
167
168
169
170
171
172
173
174
175
176
177
        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()


def _causal_conv1d_with_cp_halo(
    mixed_qkv: torch.Tensor,
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
    cp_rank: int,
    cp_size: int,
) -> torch.Tensor:
    """Run causal depthwise Conv1d with only the previous rank's boundary."""
    kernel_size = conv1d.kernel_size[0]
    dilation = conv1d.dilation[0]
    halo_width = (kernel_size - 1) * dilation
    if halo_width == 0 or cp_size == 1:
        conv_out = conv1d(mixed_qkv.transpose(1, 2))
        return F.silu(conv_out[:, :, : mixed_qkv.shape[1]]).transpose(1, 2)

    if mixed_qkv.shape[1] < halo_width:
        raise ValueError(
            "linear attention CP conv halo requires local_seq_len >= "
            f"{halo_width}, got {mixed_qkv.shape[1]}."
        )

    halo = _all_to_all_previous_rank_halo(
        mixed_qkv[:, -halo_width:, :].contiguous(),
        cp_mesh,
        cp_rank,
        cp_size,
199
200
201
202
203
204
205
206
207
208
        cp_mesh,
        cp_rank,
        cp_size,
    )
    conv_input = torch.cat((halo, mixed_qkv), dim=1).transpose(1, 2)
    conv_out = F.conv1d(
        input=conv_input,
        weight=conv1d.weight,
        bias=conv1d.bias,
        stride=conv1d.stride,
209
210
211
212
213
214
215
216
217
218
219
220
221
222
        padding=0,
        dilation=conv1d.dilation,
        groups=conv1d.groups,
    )
    return F.silu(conv_out).transpose(1, 2)


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)


class _GDNPreparedChunks(NamedTuple):
    """Reusable chunk intermediates shared by state-summary CP modes."""
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
268
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
    chunk_size: int = 64,
    use_qk_l2norm_in_kernel: bool = False,
) -> _GDNPreparedChunks:
    """Prepare GDN chunk intermediates shared by summary and local output."""
    initial_dtype = query.dtype
    if use_qk_l2norm_in_kernel:
        query = _l2norm_torch(query, dim=-1, eps=1e-6)
        key = _l2norm_torch(key, dim=-1, eps=1e-6)

    query, key, value, beta, g = [
        x.transpose(1, 2).contiguous().to(torch.float32)
        for x in (query, key, value, beta, g)
    ]

    sequence_length = key.shape[2]
    pad_size = (chunk_size - sequence_length % chunk_size) % chunk_size
    query = F.pad(query, (0, 0, 0, pad_size))
    key = F.pad(key, (0, 0, 0, pad_size))
    value = F.pad(value, (0, 0, 0, pad_size))
    beta = F.pad(beta, (0, pad_size))
    g = F.pad(g, (0, pad_size))
    total_sequence_length = sequence_length + pad_size

    query = query * (1 / (query.shape[-1] ** 0.5))
    v_beta = value * beta.unsqueeze(-1)
    k_beta = key * beta.unsqueeze(-1)
    query, key, k_beta, v_beta = [
        x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1])
        for x in (query, key, k_beta, v_beta)
    ]
    g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)

    mask = torch.triu(
        torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device),
        diagonal=0,
    )
    g = g.cumsum(dim=-1)
    decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
    attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
    for row_idx in range(1, chunk_size):
        row = attn[..., row_idx, :row_idx].clone()
        sub = attn[..., :row_idx, :row_idx].clone()
        attn[..., row_idx, :row_idx] = row + (row.unsqueeze(-1) * sub).sum(-2)
    attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)

    chunk_value = attn @ v_beta
    k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
    return _GDNPreparedChunks(
        initial_dtype=initial_dtype,
        query=query,
        key=key,
        chunk_value=chunk_value,
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def _compute_gdn_state_summary_from_prepared(
    prepared: _GDNPreparedChunks,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Compute ``state_out = M @ state_in + S`` from prepared GDN chunks."""
    key = prepared.key
    batch_size, num_heads, _, _, k_head_dim = key.shape
    v_head_dim = prepared.chunk_value.shape[-1]
    eye = torch.eye(k_head_dim, device=key.device, dtype=torch.float32).reshape(
        1, 1, k_head_dim, k_head_dim
    )
    state_ext = torch.zeros(
        batch_size,
        num_heads,
        k_head_dim,
        v_head_dim,
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        v_head_dim,
        device=key.device,
        dtype=torch.float32,
    )
    transition = eye.expand(batch_size, num_heads, -1, -1).clone()

    for chunk_idx in range(key.shape[2]):
        key_i = key[:, :, chunk_idx]
        value_i = prepared.chunk_value[:, :, chunk_idx]
        w_i = prepared.k_cumdecay[:, :, chunk_idx]
        g_i = prepared.g[:, :, chunk_idx]
        decay = g_i[:, :, -1].exp()
        key_decay = key_i * (g_i[:, :, -1, None] - g_i).exp()[..., None]

        transition_i = (
            decay[:, :, None, None] * eye
            - key_decay.transpose(-1, -2) @ w_i
        )
        state_ext_i = key_decay.transpose(-1, -2) @ value_i
        state_ext = transition_i @ state_ext + state_ext_i
        transition = transition_i @ transition

    return state_ext, transition


def _checkpoint_gdn_state_summary(
    prepared: _GDNPreparedChunks,
343
344
345
346
347
348
349
350
351
352
353
354
def _checkpoint_gdn_state_summary(
    prepared: _GDNPreparedChunks,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Compute a state summary without retaining its per-chunk autograd graph."""
    if not torch.is_grad_enabled():
        return _compute_gdn_state_summary_from_prepared(prepared)

    def recompute(
        key: torch.Tensor,
        chunk_value: torch.Tensor,
        g: torch.Tensor,
        k_cumdecay: torch.Tensor,
353
354
355
356
357
358
359
360
361
        g: torch.Tensor,
        k_cumdecay: torch.Tensor,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """Rebuild a prepared view from explicit checkpoint inputs."""
        checkpoint_prepared = prepared._replace(
            key=key,
            chunk_value=chunk_value,
            g=g,
            k_cumdecay=k_cumdecay,
359
360
361
362
363
364
365
366
367
368
369
            chunk_value=chunk_value,
            g=g,
            k_cumdecay=k_cumdecay,
        )
        return _compute_gdn_state_summary_from_prepared(checkpoint_prepared)

    return checkpoint(
        recompute,
        prepared.key,
        prepared.chunk_value,
        prepared.g,
377
378
379
380
381
382
383
384
385
386
387
388
389
390
    prepared: _GDNPreparedChunks,
    initial_state: Optional[torch.Tensor],
) -> torch.Tensor:
    """Run local GDN output using already prepared chunk intermediates."""
    query = prepared.query
    key = prepared.key
    chunk_value = prepared.chunk_value
    batch_size, num_heads, _, _, k_head_dim = key.shape
    v_head_dim = chunk_value.shape[-1]
    recurrent_state = (
        torch.zeros(
            batch_size,
            num_heads,
            k_head_dim,
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
        )
        if initial_state is None
        else initial_state.to(chunk_value)
    )
    core_attn_out = torch.zeros_like(chunk_value)

    for chunk_idx in range(0, prepared.total_sequence_length // prepared.chunk_size):
        q_i = query[:, :, chunk_idx]
        k_i = key[:, :, chunk_idx]
        v_i = chunk_value[:, :, chunk_idx]
        attn = q_i @ k_i.transpose(-1, -2) * prepared.decay_mask[:, :, chunk_idx]
        v_prime = prepared.k_cumdecay[:, :, chunk_idx] @ recurrent_state
        v_new = v_i - v_prime
        attn_inter = (
            q_i * prepared.g[:, :, chunk_idx, :, None].exp()
        ) @ recurrent_state
        core_attn_out[:, :, chunk_idx] = attn_inter + attn @ v_new
        recurrent_state = (
            recurrent_state * prepared.g[:, :, chunk_idx, -1, None, None].exp()
            + (
                k_i
                * (
418
419
420
421
422
423
424
425
426
                ).exp()[..., None]
            ).transpose(-1, -2) @ v_new
        )

    core_attn_out = core_attn_out.reshape(
        core_attn_out.shape[0],
        core_attn_out.shape[1],
        -1,
        core_attn_out.shape[-1],
424
425
426
427
428
429
430
431
432
433
        core_attn_out.shape[1],
        -1,
        core_attn_out.shape[-1],
    )
    core_attn_out = core_attn_out[:, :, :prepared.sequence_length]
    return core_attn_out.transpose(1, 2).contiguous().to(prepared.initial_dtype)


class _RecvInitialStateP2PFunction(torch.autograd.Function):
    """Receive the recurrent initial state; send its gradient in backward."""
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
        prev_rank: int,
        state_shape: tuple[int, ...],
    ) -> torch.Tensor:
        """Receive the initial state from the preceding CP rank."""
        state = torch.empty(state_shape, device=anchor.device, dtype=torch.float32)
        dist.recv(state, src=prev_rank, group=cp_group)
        ctx.cp_group = cp_group
        ctx.prev_rank = prev_rank
        return state

    @staticmethod
    def backward(ctx, grad_state: Optional[torch.Tensor]):
        if grad_state is None:
            raise RuntimeError("linear attention P2P backward missing initial-state grad.")
        dist.send(grad_state.contiguous(), dst=ctx.prev_rank, group=ctx.cp_group)
        return None, None, None, None


class _SendFinalStateP2PFunction(torch.autograd.Function):
    """Send the recurrent final state; receive its gradient in backward."""
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
        cp_group,
        next_rank: int,
    ) -> torch.Tensor:
        """Send the final state to the succeeding CP rank."""
        dist.send(final_state.contiguous(), dst=next_rank, group=cp_group)
        ctx.cp_group = cp_group
        ctx.next_rank = next_rank
        ctx.state_shape = tuple(final_state.shape)
        ctx.state_dtype = final_state.dtype
        return final_state.new_zeros(())

    @staticmethod
    def backward(ctx, grad_token: torch.Tensor):
        grad_state = torch.empty(
            ctx.state_shape,
            device=grad_token.device,
            dtype=ctx.state_dtype,
        )
        dist.recv(grad_state, src=ctx.next_rank, group=ctx.cp_group)
        return grad_state, None, None


def _apply_gdn_state_summary(
    state_ext: torch.Tensor,
489
490
491
492
493
494
495
496
497
498
499
    transition: torch.Tensor,
    initial_state: Optional[torch.Tensor],
) -> torch.Tensor:
    """Apply ``state_out = M @ state_in + S`` to an incoming GDN state."""
    if initial_state is None:
        return state_ext
    return transition @ initial_state.to(transition) + state_ext


def _gdn_state_p2p_summary(
    query: torch.Tensor,
514
515
516
517
518
519
520
521
522
523
    The rank-ordered critical path then contains only ``M @ state + S`` and
    the small state transfer. Token outputs retain the ordinary PyTorch graph,
    while the two custom autograd boundaries reverse the state communication.
    """
    if cp_size == 1:
        core_attn_out, _ = torch_chunk_gated_delta_rule(
            query,
            key,
            value,
            g=g,
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
            output_final_state=False,
            chunk_size=chunk_size,
            use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
        )
        return core_attn_out

    cp_group = cp_mesh.get_group()
    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
    state_shape = (query.shape[0], value.shape[2], query.shape[3], value.shape[3])

    prepared = _prepare_gdn_chunks_for_summary(
        query,
        key,
        value,
        g,
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        beta,
        chunk_size=chunk_size,
        use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel,
    )
    state_ext = None
    transition = None
    if cp_rank < cp_size - 1:
        state_ext, transition = _checkpoint_gdn_state_summary(prepared)

    initial_state = None
    if cp_rank > 0:
        initial_state = _RecvInitialStateP2PFunction.apply(
            query,
            cp_group,
            prev_rank,
            state_shape,
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
            prev_rank,
            state_shape,
        )

    send_token = None
    if cp_rank < cp_size - 1:
        final_state = _apply_gdn_state_summary(
            state_ext,
            transition,
            initial_state,
        )
        send_token = _SendFinalStateP2PFunction.apply(final_state, cp_group, next_rank)

    core_attn_out = _run_prepared_gdn_chunks(prepared, initial_state)
    if send_token is not None:
        core_attn_out = core_attn_out + send_token.to(core_attn_out.dtype) * 0

    return core_attn_out


class _GDNStateP2PTritonFunction(torch.autograd.Function):
    """Pipeline fused affine GDN states over sequence-sharded CP ranks."""
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
        prev_rank: int,
        next_rank: int,
    ) -> torch.Tensor:
        """Run fused local GDN and forward its affine state across CP ranks."""
        from hyper_parallel.platform.torch.custom_ops.gdn.chunk_gated_delta_rule 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,
        )
        from hyper_parallel.platform.torch.custom_ops.gdn.state_summary import (  # pylint: disable=import-outside-toplevel
            apply_gdn_state_summary,
            chunk_gated_delta_rule_state_summary_fwd,
        )

        (
            query_norm,
            key_norm,
            _,
            _,
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
            g,
            beta,
            use_qk_l2norm_in_kernel=False,
        )
        initial_state = None
        recv_buffer = None
        recv_work = None
        if cp_rank > 0:
            recv_buffer = torch.empty(
                (query.shape[0], query.shape[2], query.shape[3], value.shape[3]),
                device=query.device,
                dtype=torch.float32,
            )
            recv_work = dist.irecv(recv_buffer, src=prev_rank, group=cp_group)

        state_ext = None
        transition = None
        if cp_rank < cp_size - 1:
            state_ext, transition = chunk_gated_delta_rule_state_summary_fwd(
                key_norm,
                w,
                u,
                g_cumsum,
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
                u,
                g_cumsum,
            )

        if recv_work is not None:
            recv_work.wait()
            initial_state = recv_buffer

        send_buffer = None
        send_work = None
        if cp_rank < cp_size - 1:
            send_buffer = apply_gdn_state_summary(
                state_ext,
                transition,
                initial_state,
            ).contiguous()
            send_work = dist.isend(send_buffer, dst=next_rank, group=cp_group)

        h, v_new, _ = chunk_gated_delta_rule_fwd_apply_state_saved(
            key_norm,
            g_cumsum,
            w,
            u,
661
662
663
664
665
666
667
668
669
            u,
            initial_state=initial_state,
            output_final_state=False,
        )
        output = chunk_gated_delta_rule_fwd_output_saved(
            query_norm,
            key_norm,
            g_cumsum,
            h,
670
671
672
673
674
675
676
677
678
679
680
681
682
            v_new,
            scale,
        ).to(query.dtype)

        if send_work is not None:
            send_work.wait()

        empty = query.new_empty(0)
        ctx.save_for_backward(
            query_norm,
            key_norm,
            value,
            g_cumsum,
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
            matrix_a,
            initial_state if initial_state is not None else empty,
            transition if transition is not None else empty,
        )
        ctx.has_initial_state = initial_state is not None
        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, grad_output: torch.Tensor):  # pylint: disable=too-many-locals
        """Backpropagate local GDN tensors and the state gradient wavefront."""
        from hyper_parallel.platform.torch.custom_ops.gdn.chunk_gated_delta_rule import (  # pylint: disable=import-outside-toplevel
            chunk_gated_delta_rule_bwd_finish_saved,
            chunk_gated_delta_rule_bwd_prepare_saved,
            chunk_gated_delta_rule_bwd_state_saved,
        )
        from hyper_parallel.platform.torch.custom_ops.gdn.state_summary import (  # pylint: disable=import-outside-toplevel
            apply_gdn_state_gradient_summary,
            chunk_gated_delta_rule_state_gradient_summary_bwd,
        )

        (
            query,
            key,
            value,
            g_cumsum,
716
717
718
719
720
721
722
723
724
725
726
727
            matrix_a,
            initial_state,
            transition,
        ) = ctx.saved_tensors
        if not ctx.has_initial_state:
            initial_state = None

        w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare_saved(
            query,
            key,
            value,
            g_cumsum,
731
732
733
734
735
736
737
738
739
740
741
            grad_output,
            ctx.scale,
        )

        grad_state_ext = None
        if ctx.cp_rank > 0:
            grad_state_ext = chunk_gated_delta_rule_state_gradient_summary_bwd(
                query,
                key,
                w,
                g_cumsum,
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
                dv,
                ctx.scale,
            )

        grad_final_state = None
        recv_work = None
        if ctx.cp_rank < ctx.cp_size - 1:
            recv_buffer = torch.empty(
                (query.shape[0], query.shape[2], query.shape[3], value.shape[3]),
                device=grad_output.device,
                dtype=torch.float32,
            )
            recv_work = dist.irecv(
                recv_buffer,
                src=ctx.next_rank,
                group=ctx.cp_group,
            )
        if recv_work is not None:
            recv_work.wait()
            grad_final_state = recv_buffer

        send_buffer = None
        send_work = None
        if ctx.cp_rank > 0:
            send_buffer = apply_gdn_state_gradient_summary(
                grad_state_ext,
                transition,
                grad_final_state,
            ).contiguous()
            send_work = dist.isend(
                send_buffer,
                dst=ctx.prev_rank,
                group=ctx.cp_group,
            )
774
775
776
777
778
779
780
781
782
                dst=ctx.prev_rank,
                group=ctx.cp_group,
            )

        dh, _, dv = chunk_gated_delta_rule_bwd_state_saved(
            query,
            key,
            g_cumsum,
            w,
785
786
787
788
789
790
791
792
793
794
            grad_output,
            dv,
            ctx.scale,
        )
        empty = query.new_empty(0)
        dq, dk, dv, dg, dbeta = chunk_gated_delta_rule_bwd_finish_saved(
            query,
            key,
            query,
            key,
807
808
809
810
811
812
813
814
815
816
817
            ctx.scale,
            use_qk_l2norm_in_kernel=False,
        )

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


def _gdn_state_p2p_triton(
    query: torch.Tensor,
823
824
825
826
827
828
829
830
831
832
    cp_rank: int,
    cp_size: int,
) -> torch.Tensor:
    """Run fused local GDN with an affine state wavefront."""
    if cp_size == 1:
        output, _ = chunk_gated_delta_rule(
            query,
            key,
            value,
            g=g,
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
            output_final_state=False,
            use_qk_l2norm_in_kernel=True,
            backend="triton",
        )
        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,
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
    Shard(split_dim)`` redistribution for a 1-D mesh. It uses platform-level
    differentiable all-to-all directly to avoid wrapping each activation in a
    temporary DTensor.
    """
    split_count = device_mesh.size()
    if split_count == 1:
        return tensor

    original_shape = tuple(tensor.shape)
    dim_size = original_shape[split_dim]
    if dim_size % split_count != 0:
        raise ValueError(
            f"linear attention all-to-all split dim {split_dim} with size "
            f"{dim_size} must be divisible by cp_size {split_count}."
        )

    split_size = dim_size // split_count
    final_shape = list(original_shape)
    if split_dim != concat_dim:
        final_shape[split_dim] = split_size
        final_shape[concat_dim] = final_shape[concat_dim] * split_count
    final_shape = tuple(final_shape)

    reshape_dims = list(original_shape)
    reshape_dims[split_dim] = split_count
    reshape_dims.insert(split_dim + 1, split_size)

    trans_dims = list(range(len(reshape_dims)))
    trans_dims.remove(split_dim)
    trans_dims.insert(0, split_dim)

    a2a_input = tensor.reshape(reshape_dims).permute(trans_dims).contiguous()
    reshape_shape = list(a2a_input.shape)
    reshape_shape[0] = reshape_shape[0] * reshape_shape[1]
    reshape_shape.pop(1)
    a2a_input = a2a_input.reshape(reshape_shape)

    a2a_input = a2a_input.contiguous()
    split_len = a2a_input.shape[0] // split_count
    input_splits = [split_len] * split_count
    output_splits = [split_len] * split_count
    output = platform.differentiable_all_to_all_single(
        a2a_input,
        input_splits,
        output_splits,
        group=device_mesh.get_group(),
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
        output_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)

    out_trans_dims = list(range(len(output_reshape)))
    first_dim = out_trans_dims.pop(0)
    if concat_dim >= len(out_trans_dims):
        out_trans_dims.append(first_dim)
    else:
        out_trans_dims.insert(concat_dim, first_dim)

    final_output = output.reshape(output_reshape).permute(out_trans_dims).contiguous()
    final_reshape = list(final_output.shape)
    if concat_dim < len(final_reshape) - 1:
        final_reshape[concat_dim] = (
            final_reshape[concat_dim] * final_reshape[concat_dim + 1]
        )
        final_reshape.pop(concat_dim + 1)

    return final_output.reshape(final_reshape).view(final_shape)


class GatedDeltaNetUlyssesCP(nn.Module):
    """Pure-Ulysses CP execution wrapper for a Qwen3.5 Gated DeltaNet module.
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
        *,
        backend: str = "eager",
        chunk_size: int = 64,
    ):
        super().__init__()
        self.module = module
        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 chunk_size <= 0:
            raise ValueError(f"chunk_size must be positive, got {chunk_size}.")
        if backend == "triton" and chunk_size != 64:
            raise NotImplementedError("GDN Triton backend requires chunk_size=64.")
        self.gdn_backend = backend
        self.chunk_size = chunk_size
        self.cp_mesh = _ensure_1d(device_mesh)
        self.cp_size = self.cp_mesh.size()
        self.cp_rank = self.cp_mesh.get_local_rank()
        self.seq_dim = 1
        self.head_dim = 2
        self._validate_module()

    def _validate_module(self) -> None:
        """Validate the wrapped GDN module and Ulysses layout constraints."""
        required = (
            "in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a",
            "conv1d", "A_log", "dt_bias", "norm", "out_proj",
            "num_k_heads", "num_v_heads", "head_k_dim", "head_v_dim",
            "key_dim", "value_dim", "conv_dim",
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
            "conv1d", "A_log", "dt_bias", "norm", "out_proj",
            "num_k_heads", "num_v_heads", "head_k_dim", "head_v_dim",
            "key_dim", "value_dim", "conv_dim",
        )
        missing = [name for name in required if not hasattr(self.module, name)]
        if missing:
            raise TypeError(
                "Qwen3.5 GDN layer is missing required attributes: "
                + ", ".join(missing)
            )
        if self.cp_size <= 1:
            return
        if self.module.num_k_heads % self.cp_size != 0:
            raise ValueError(
                f"linear attention num_k_heads ({self.module.num_k_heads}) must be "
                f"divisible by cp_size ({self.cp_size}) for Ulysses CP."
            )
        if self.module.num_v_heads % self.cp_size != 0:
            raise ValueError(
                f"linear attention num_v_heads ({self.module.num_v_heads}) must be "
                f"divisible by cp_size ({self.cp_size}) for Ulysses CP."
            )
        if self.module.num_v_heads % self.module.num_k_heads:
            raise ValueError("GDN num_v_heads must be divisible by num_k_heads.")
        _validate_gdn_activation(self.module)

    def _seq_to_head(self, tensor: torch.Tensor) -> torch.Tensor:
        return _differentiable_all_to_all_shard(
            tensor,
            self.cp_mesh,
            split_dim=self.head_dim,
            concat_dim=self.seq_dim,
1014
1015
1016
1017
1018
1019
1020
1021
1022
            concat_dim=self.seq_dim,
        )

    def _head_to_seq(self, tensor: torch.Tensor) -> torch.Tensor:
        return _differentiable_all_to_all_shard(
            tensor,
            self.cp_mesh,
            split_dim=self.seq_dim,
            concat_dim=self.head_dim,
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
        b: torch.Tensor,
        a: torch.Tensor,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        """Pack Q/K/V/B/A by CP rank and run a single seq-to-head all-to-all."""
        if self.cp_size == 1:
            return q_proj, k_proj, v_proj, b, a

        base = self.module
        local_key_dim = base.key_dim // self.cp_size
        local_value_dim = base.value_dim // self.cp_size
        local_num_v_heads = base.num_v_heads // self.cp_size

        q_chunks = torch.split(q_proj, local_key_dim, dim=-1)
        k_chunks = torch.split(k_proj, local_key_dim, dim=-1)
        v_chunks = torch.split(v_proj, local_value_dim, dim=-1)
        b_chunks = torch.split(b, local_num_v_heads, dim=-1)
        a_chunks = torch.split(a, local_num_v_heads, dim=-1)
        rank_major_chunks = [
            torch.cat(chunks, dim=-1)
            for chunks in zip(q_chunks, k_chunks, v_chunks, b_chunks, a_chunks)
        ]
        packed = torch.cat(rank_major_chunks, dim=-1).contiguous()
        packed = self._seq_to_head(packed)
        return torch.split(
            packed,
            [
                local_key_dim,
                local_key_dim,
1062
1063
1064
1065
1066
1067
1068
1069
1070
            dim=-1,
        )

    def _local_conv_weight(self) -> torch.Tensor:
        return _slice_qkv_local_cp(
            self.module.conv1d.weight,
            key_dim=self.module.key_dim,
            value_dim=self.module.value_dim,
            dim=0,
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
            cp_size=self.cp_size,
        )

    def _local_conv_bias(self) -> Optional[torch.Tensor]:
        bias = self.module.conv1d.bias
        if bias is None:
            return None
        return _slice_qkv_local_cp(
            bias,
            key_dim=self.module.key_dim,
            value_dim=self.module.value_dim,
            dim=0,
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
        attention_mask: Optional[torch.Tensor] = None,
        **kwargs,
    ) -> torch.Tensor:
        """Run Gated DeltaNet with pure Ulysses context parallel."""
        if cache_params is not None:
            raise NotImplementedError("GDN Ulysses CP currently supports training without cache only.")
        if (
            kwargs.get("cu_seq_lens_q") is not None
            or kwargs.get("seq_idx") is not None
        ):
            raise NotImplementedError("Packed variable-length GDN Ulysses CP is not implemented.")
        hidden_states = _local_tensor_at_cp_boundary(hidden_states)
        if self.gdn_backend == "triton" and hidden_states.shape[1] % 64:
            raise NotImplementedError(
                "GDN Ulysses Triton backend requires each rank's local "
                f"sequence length ({hidden_states.shape[1]}) divisible by 64."
            )

        base = self.module
        hidden_states = _apply_local_padding_mask(hidden_states, attention_mask)

        bsz, local_seq_len, _ = hidden_states.shape
        mixed_qkv = base.in_proj_qkv(hidden_states)
        z = base.in_proj_z(hidden_states).reshape(
            bsz,
            local_seq_len,
            base.num_v_heads,
            base.head_v_dim,
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
            local_seq_len,
            base.num_v_heads,
            base.head_v_dim,
        )
        b = base.in_proj_b(hidden_states)
        a = base.in_proj_a(hidden_states)

        q_proj, k_proj, v_proj = torch.split(
            mixed_qkv,
            [base.key_dim, base.key_dim, base.value_dim],
            dim=-1,
        )
        q_proj, k_proj, v_proj, b, a = self._seq_to_head_qkvba(
            q_proj, k_proj, v_proj, b, a
        )

        full_seq_len = q_proj.shape[1]
        local_key_dim = base.key_dim // self.cp_size
        local_value_dim = base.value_dim // self.cp_size
        local_num_k_heads = base.num_k_heads // self.cp_size
        local_num_v_heads = base.num_v_heads // self.cp_size
        local_conv_dim = local_key_dim * 2 + local_value_dim

        mixed_qkv = torch.cat((q_proj, k_proj, v_proj), dim=-1).transpose(1, 2)
        conv_out = F.conv1d(
            input=mixed_qkv,
            weight=self._local_conv_weight(),
            bias=self._local_conv_bias(),
            stride=base.conv1d.stride,
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
            padding=base.conv1d.padding,
            dilation=base.conv1d.dilation,
            groups=local_conv_dim,
        )
        mixed_qkv = F.silu(conv_out[:, :, :full_seq_len]).transpose(1, 2)

        query, key, value = torch.split(
            mixed_qkv,
            [local_key_dim, local_key_dim, local_value_dim],
            dim=-1,
        )
        query = query.reshape(bsz, full_seq_len, local_num_k_heads, base.head_k_dim)
        key = key.reshape(bsz, full_seq_len, local_num_k_heads, base.head_k_dim)
        value = value.reshape(bsz, full_seq_len, local_num_v_heads, base.head_v_dim)

        a_log = _slice_local_cp(base.A_log, 0, self.cp_rank, self.cp_size)
        dt_bias = _slice_local_cp(base.dt_bias, 0, self.cp_rank, self.cp_size)
        beta = b.sigmoid()
        g = -a_log.float().exp() * F.softplus(a.float() + dt_bias)

        kv_groups = _kv_groups(base)
        if kv_groups > 1:
            query = query.repeat_interleave(kv_groups, dim=2)
            key = key.repeat_interleave(kv_groups, dim=2)

        core_attn_out, _ = chunk_gated_delta_rule(
            query,
            key,
            value,
            g=g,
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
            use_qk_l2norm_in_kernel=True,
            backend=self.gdn_backend,
        )

        core_attn_out = self._head_to_seq(core_attn_out)
        core_attn_out = core_attn_out.reshape(-1, base.head_v_dim)
        z_flat = z.reshape(-1, base.head_v_dim)
        core_attn_out = base.norm(core_attn_out, z_flat)
        core_attn_out = core_attn_out.reshape(bsz, local_seq_len, base.value_dim)
        if hasattr(base, "out_proj_input"):
            core_attn_out = base.out_proj_input(core_attn_out)
        return base.out_proj(core_attn_out)


class GatedDeltaNetP2PCP(nn.Module):
    """Sequence-sharded GDN CP with an affine-summary state wavefront."""
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
        *,
        backend: str = "eager",
        chunk_size: int = 64,
    ):
        super().__init__()
        self.module = module
        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 chunk_size <= 0:
            raise ValueError(f"chunk_size must be positive, got {chunk_size}.")
        if backend == "triton" and chunk_size != 64:
            raise NotImplementedError("GDN Triton backend requires chunk_size=64.")
        self.gdn_backend = backend
        self.chunk_size = chunk_size
        self.cp_mesh = _ensure_1d(device_mesh)
        self.cp_size = self.cp_mesh.size()
        self.cp_rank = self.cp_mesh.get_local_rank()
        self._validate_module()

    def _validate_module(self) -> None:
        """Validate the Conv1d requirements of the P2P CP path."""
        required = (
            "in_proj_qkv", "in_proj_z", "in_proj_b", "in_proj_a",
            "conv1d", "A_log", "dt_bias", "norm", "out_proj",
            "num_k_heads", "num_v_heads", "head_k_dim", "head_v_dim",
            "key_dim", "value_dim", "conv_dim",
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
            "conv1d", "A_log", "dt_bias", "norm", "out_proj",
            "num_k_heads", "num_v_heads", "head_k_dim", "head_v_dim",
            "key_dim", "value_dim", "conv_dim",
        )
        missing = [name for name in required if not hasattr(self.module, name)]
        if missing:
            raise TypeError(
                "Qwen3.5 GDN layer is missing required attributes: "
                + ", ".join(missing)
            )
        if self.gdn_backend == "triton" and (
            self.module.head_k_dim != 128 or self.module.head_v_dim != 128
        ):
            raise NotImplementedError(
                "linear attention P2P Triton backend requires "
                "head_k_dim=head_v_dim=128."
            )
        if self.module.num_v_heads % self.module.num_k_heads:
            raise ValueError("GDN num_v_heads must be divisible by num_k_heads.")
        _validate_gdn_activation(self.module)
        conv = self.module.conv1d
        if conv.stride != (1,):
            raise ValueError(
                "linear attention P2P CP currently supports only conv1d stride=1."
            )
        if conv.groups != self.module.conv_dim:
            raise ValueError(
                "linear attention P2P CP expects depthwise conv1d groups=conv_dim."
            )
        if (
            conv.in_channels != self.module.conv_dim
            or conv.out_channels != self.module.conv_dim
        ):
            raise ValueError(
                "linear attention P2P CP expects conv1d channels to match conv_dim."
            )

    def _conv1d_with_halo(self, mixed_qkv: torch.Tensor) -> torch.Tensor:
1263
1264
1265
1266
1267
1268
1269
1270
1271
            )

    def _conv1d_with_halo(self, mixed_qkv: torch.Tensor) -> torch.Tensor:
        """Run local Conv1d after exchanging only the previous-rank halo."""
        return _causal_conv1d_with_cp_halo(
            mixed_qkv,
            self.module.conv1d,
            self.cp_mesh,
            self.cp_rank,
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
        attention_mask: Optional[torch.Tensor] = None,
        **kwargs,
    ) -> torch.Tensor:
        """Run Gated DeltaNet on local sequence shards with recurrent-state P2P."""
        if cache_params is not None:
            raise NotImplementedError("GDN P2P CP currently supports training without cache only.")
        if (
            kwargs.get("cu_seq_lens_q") is not None
            or kwargs.get("seq_idx") is not None
        ):
            raise NotImplementedError("Packed variable-length GDN P2P is not implemented.")
        hidden_states = _local_tensor_at_cp_boundary(hidden_states)

        base = self.module
        hidden_states = _apply_local_padding_mask(hidden_states, attention_mask)

        bsz, local_seq_len, _ = hidden_states.shape
        mixed_qkv = base.in_proj_qkv(hidden_states)
        z = base.in_proj_z(hidden_states).reshape(
            bsz,
            local_seq_len,
            base.num_v_heads,
            base.head_v_dim,
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
            local_seq_len,
            base.num_v_heads,
            base.head_v_dim,
        )
        b = base.in_proj_b(hidden_states)
        a = base.in_proj_a(hidden_states)

        mixed_qkv = self._conv1d_with_halo(mixed_qkv)
        query, key, value = torch.split(
            mixed_qkv,
            [base.key_dim, base.key_dim, base.value_dim],
            dim=-1,
        )
        query = query.reshape(bsz, local_seq_len, base.num_k_heads, base.head_k_dim)
        key = key.reshape(bsz, local_seq_len, base.num_k_heads, base.head_k_dim)
        value = value.reshape(bsz, local_seq_len, base.num_v_heads, base.head_v_dim)

        beta = b.sigmoid()
        g = -base.A_log.float().exp() * F.softplus(a.float() + base.dt_bias)

        kv_groups = _kv_groups(base)
        if kv_groups > 1:
            query = query.repeat_interleave(kv_groups, dim=2)
            key = key.repeat_interleave(kv_groups, dim=2)

        if self.gdn_backend == "triton":
            if local_seq_len % 64 != 0:
                raise NotImplementedError(
                    "linear attention P2P Triton backend requires each CP "
                    f"rank's local sequence length ({local_seq_len}) to be "
                    "divisible by 64."
                )
            if not is_triton_gdn_available(query, key, value, g, beta):
                raise RuntimeError(
                    "linear attention P2P Triton backend requires an NPU "
                    "input satisfying the fixed GDN contract and a validated "
                    "triton-ascend >= 3.2.1 installation."
                )
            core_attn_out = _gdn_state_p2p_triton(
                query,
                key,
                value,
                g,
1344
1345
1346
1347
1348
1349
1350
1351
1352
                self.cp_rank,
                self.cp_size,
            )
        else:
            core_attn_out = _gdn_state_p2p_summary(
                query,
                key,
                value,
                g,
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
                chunk_size=self.chunk_size,
                use_qk_l2norm_in_kernel=True,
            )

        core_attn_out = core_attn_out.reshape(-1, base.head_v_dim)
        z_flat = z.reshape(-1, base.head_v_dim)
        core_attn_out = base.norm(core_attn_out, z_flat)
        core_attn_out = core_attn_out.reshape(bsz, local_seq_len, base.value_dim)
        if hasattr(base, "out_proj_input"):
            core_attn_out = base.out_proj_input(core_attn_out)
        return base.out_proj(core_attn_out)



__all__ = ["GatedDeltaNetP2PCP", "GatedDeltaNetUlyssesCP"]