1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""GDN Ulysses and state-CP scheduling over the complete local algorithm."""
16from __future__ import annotations
17import math
18from typing import Any, Optional
19
20import torch
21import torch.distributed as dist
22from torch.nn import functional as F
23from torch.autograd.function import once_differentiable
24
25from hyper_parallel.components.functional.gated_delta_net import (
26 chunk_gated_delta_rule, is_triton_gdn_available, apply_gdn_state_summary, apply_gdn_state_gradient_summary,
27)
28from hyper_parallel.components.functional.gated_delta_net_ascendc import (
29 GDNNativePrepared, load_gdn_native_state_ops, prepare_gdn_native, finish_gdn_native_forward,
30)
31from hyper_parallel.components.functional.linear_attention_convolution import fused_causal_conv1d, packed_causal_conv1d
32from hyper_parallel.components.modules.attention.linear_attention_utils.layer_adapter import (
33 prepare_linear_attention_input,
34)
35from hyper_parallel.components.modules.attention.linear_attention_utils.cp_convolution import (
36 causal_convolutions_with_halo,
37)
38from hyper_parallel.components.modules.attention.linear_attention_utils.parallel_layout import (
39 validate_linear_attention_layout, split_linear_attention_mesh,
40)
41from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import (
42 PackedSequenceInfo, local_chunk_metadata,
43)
44from hyper_parallel.core.dtensor.device_mesh import DeviceMesh
45from hyper_parallel.distributed.context_parallel.collectives import exchange_sequence_heads
46from hyper_parallel.distributed.module_binding import ParallelModuleSpec
47from hyper_parallel.components.modules.attention.linear_attention_utils.cp_state_exchange import (
48 NativeStateAllGather, NativeStateExchange, native_state_intervals,
49)
50from .gated_delta_net import GatedDeltaNetModule
51
52
53# Convert natural-log decay to the log2 convention of native CP summary kernels.
54LOG2_E = 1.0 / math.log(2.0)
55
56
57class CPGatedDeltaNetModule(GatedDeltaNetModule):
58 """GDN Ulysses and state CP execution sharing the complete local layer math."""
59
60 def __init__(self, *, config: Any = None, module: torch.nn.Module | None = None,
61 module_fqn: str = "", context: Any = None, backend: str = "eager",
62 conv_backend: str | None = None, chunk_size: int = 64,
63 input_layout: str = "BSH", ulysses_degree: int | None = 1,
64 state_cp_method: str = "p2p",
65 p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False) -> None:
66 """Retain the explicitly requested algorithm and deferred CP resources."""
67 del module_fqn, context
68 self.ulysses_degree = ulysses_degree
69 self.state_cp_method = state_cp_method
70 self.p2p_head_chunks = p2p_head_chunks
71 if reuse_cp_state_on_recompute and backend != "ascendc":
72 raise NotImplementedError("Checkpoint entry caching currently requires the Ascend C state backend.")
73 self.reuse_cp_state_on_recompute, self._cp_entry_key = reuse_cp_state_on_recompute, object()
74 self.state_cp = None
75 if conv_backend is None and ulysses_degree == 1:
76 conv_backend = "eager"
77 super().__init__(config=config, module=module,
78 backend=backend, conv_backend=conv_backend, chunk_size=chunk_size, input_layout=input_layout)
79 self.cp_rank, self.cp_size = 0, 1
80 self.ulysses_size, self.state_size = 1, 1
81 self.ulysses_mesh = self.state_mesh = None
82 self.ulysses_rank = 0
83 self.cp_context = None
84 self.convolve_after_exchange = ulysses_degree is None
85
86 def prepare_input(self, hidden_states: torch.Tensor, options: dict) -> tuple:
87 """Resolve real document boundaries against this CP rank's physical shard.
88
89 Args:
90 hidden_states: Local dense or flat hidden activations.
91 options: Explicit backend options or invocation document metadata.
92 """
93 return prepare_linear_attention_input(hidden_states, options, self.cp_rank, self.cp_size)
94
95 def parallel_module_spec(self) -> ParallelModuleSpec:
96 """Expose the complete pipeline with internal state exchange owned by autograd."""
97 return ParallelModuleSpec("attention.gdn.cp", "cp",
98 {"execute_attention_pipeline": ("operands", "info")},
99 validate=validate_linear_attention_layout)
100
101 def bind_parallel(self, binding: Any) -> None:
102 """Borrow a full CP context once, preserving GDN's currently qualified modes.
103
104 Args:
105 binding: Resolved parallel binding containing the CP context.
106 """
107 if binding.cp_context is None:
108 raise ValueError("GDN CP requires CPContext")
109 self.cp_context = binding.cp_context
110 self.cp_rank, self.cp_size = self.cp_context.rank, self.cp_context.size
111 degree = self.cp_size if self.ulysses_degree is None else self.ulysses_degree
112 if not isinstance(degree, int) or isinstance(degree, bool) or degree < 1 or self.cp_size % degree:
113 raise ValueError("GDN Ulysses degree must divide CP size")
114 self.ulysses_size, self.state_size = degree, self.cp_size // degree
115 self.convolve_after_exchange = self.ulysses_degree is None or (1 < self.cp_size == degree)
116 if self.num_k_heads % degree or self.num_v_heads % degree:
117 raise ValueError("GDN Ulysses degree must divide query and value heads")
118 self._bind_state_groups(degree)
119
120 def _bind_state_groups(self, degree: int) -> None:
121 """Create head-shard state groups once, retaining the parent root mapping."""
122 self.state_mesh = self.cp_context.mesh
123 if 1 < degree < self.cp_size:
124 if self.backend != "ascendc":
125 raise NotImplementedError("GDN hybrid Ulysses/state CP currently requires Ascend C")
126 hybrid = split_linear_attention_mesh(self.state_mesh, degree, ("gdn_state", "gdn_ulysses"))
127 self.state_mesh, self.ulysses_mesh = hybrid["gdn_state"], hybrid["gdn_ulysses"]
128 self.ulysses_rank = self.ulysses_mesh.get_local_rank()
129 if not self.convolve_after_exchange and self.cp_size > 1:
130 if self.backend not in ("triton", "ascendc"):
131 raise NotImplementedError("GDN state CP requires Triton or Ascend C")
132 if self.state_cp_method == "allgather":
133 ranks = tuple(self.state_mesh.rank_list)
134 if ranks != tuple(dist.get_process_group_ranks(self.state_mesh.get_group())):
135 raise ValueError("GDN AllGather requires the mesh order to match the communication group's order")
136 self.state_cp = NativeStateAllGather(
137 self.state_mesh.get_group(), self.state_mesh.get_local_rank(), self.state_size)
138
139 def _exchange_raw_inputs(self, operands: tuple) -> tuple:
140 """Exchange packed Q/K/V and gates before pure-Ulysses convolution."""
141 mixed, beta, decay = operands
142 if self.cp_size == 1:
143 return mixed, beta, decay
144 widths = (self.conv_dim // self.cp_size, self.num_v_heads // self.cp_size,
145 self.num_v_heads // self.cp_size)
146 chunks = [tensor.split(width, dim=-1) for tensor, width in zip((mixed, beta, decay), widths)]
147 packed = torch.cat([torch.cat(parts, dim=-1) for parts in zip(*chunks)], dim=-1).contiguous()
148 packed = exchange_sequence_heads(packed, self.cp_context.mesh, split_dim=2, concat_dim=1)
149 return packed.split(widths, dim=-1)
150
151 def _local_conv_parameter(self, parameter: torch.Tensor | None) -> torch.Tensor | None:
152 if parameter is None:
153 return None
154 width = self.conv_dim // self.cp_size
155 return parameter.narrow(0, self.cp_rank * width, width)
156
157 def _convolve_local_heads(self, mixed: torch.Tensor, info: PackedSequenceInfo | None) -> torch.Tensor:
158 conv = self.conv1d
159 weight, bias = self._local_conv_parameter(conv.weight), self._local_conv_parameter(conv.bias)
160 if info is not None:
161 return packed_causal_conv1d(mixed, conv, info, weight=weight, bias=bias, backend=self.conv_backend)
162 if self.conv_backend != "eager":
163 return fused_causal_conv1d(mixed, weight, bias, backend=self.conv_backend, dilation=conv.dilation[0])
164 output = torch.conv1d(mixed.transpose(1, 2), weight, bias, stride=conv.stride,
165 padding=conv.padding, dilation=conv.dilation, groups=mixed.shape[-1])
166 return F.silu(output[:, :, :mixed.shape[1]]).transpose(1, 2)
167
168 def execute_attention_pipeline(self, operands: tuple, info: PackedSequenceInfo | None) -> torch.Tensor:
169 """Exchange tokens before pure-U convolution, or exchange states inside P2P autograd.
170
171 Args:
172 operands: Projected inputs consumed by this attention stage.
173 info: Immutable packed-sequence metadata, or None for dense input.
174 """
175 if self.cp_context is None:
176 raise RuntimeError("Bind GDN CP resources before forward")
177 if self.convolve_after_exchange:
178 mixed, beta, decay = self._exchange_raw_inputs(operands)
179 info = None if info is None else info.ulysses(self.cp_size, self.cp_rank)
180 mixed = self._convolve_local_heads(mixed, info)
181 heads = self.num_v_heads // self.cp_size
182 a_log = self.A_log.narrow(0, self.cp_rank * heads, heads)
183 dt_bias = self.dt_bias.narrow(0, self.cp_rank * heads, heads)
184 inputs = self.prepare_core_inputs(mixed, beta, decay, self.cp_size, a_log, dt_bias)
185 output = self.run_local_core(inputs, info)
186 return (output if self.cp_size == 1 else
187 exchange_sequence_heads(output, self.cp_context.mesh, split_dim=1, concat_dim=2))
188 mixed, beta, decay = operands
189 mixed, = causal_convolutions_with_halo((mixed,), (self.conv1d,), self.cp_context.mesh,
190 self.cp_rank, self.cp_size, sequence_info=info,
191 backend=self.conv_backend)
192 inputs = self.prepare_core_inputs(mixed, beta, decay)
193 if self.ulysses_mesh is not None:
194 # Convolution and raw gates retain their original token ownership.
195 # Equal Q/K and V splits preserve each compact GVA group.
196 inputs = tuple(exchange_sequence_heads(tensor, self.ulysses_mesh, split_dim=2, concat_dim=1)
197 for tensor in inputs)
198 info = None if info is None else info.ulysses(self.ulysses_size, self.ulysses_rank)
199 output = self._run_state_core(inputs, info)
200 return (output if self.ulysses_mesh is None else
201 exchange_sequence_heads(output, self.ulysses_mesh, split_dim=1, concat_dim=2))
202
203 def _run_state_core(self, inputs: tuple, info: PackedSequenceInfo | None) -> torch.Tensor:
204 """Execute local phases on this head shard's chronological state group."""
205 if self.backend == "triton":
206 if not is_triton_gdn_available(*inputs):
207 raise RuntimeError("GDN P2P Triton requires the fixed NPU BF16 K=V=128 contract")
208 return triton_state_gdn(*inputs, self.state_mesh, self.state_mesh.get_local_rank(), self.state_size,
209 sequence_info=info)
210 if self.backend == "ascendc" and self.state_size > 1:
211 return ascendc_state_gdn(
212 *inputs, cp_mesh=self.state_mesh, state_cp=self.state_cp, sequence_info=info,
213 p2p_head_chunks=self.p2p_head_chunks,
214 reuse_cp_state_on_recompute=self.reuse_cp_state_on_recompute, cache_key=self._cp_entry_key)
215 return self.run_local_core(inputs, info)
216
217
218def _global_peer_rank(cp_mesh: DeviceMesh, local_rank: int) -> int:
219 """Map a CP-local rank index to its global distributed rank."""
220 return int(cp_mesh.rank_list[local_rank])
221
222
223def _l2norm_torch(x: torch.Tensor, dim: int = -1, eps: float = 1e-6) -> torch.Tensor:
224 """Match the pure torch GDN reference l2norm helper."""
225 return (x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)).to(x.dtype)
226
227
228def _prepare_gdn_forward_send(key_norm, w, u, g_cumsum, send_next, sequence_info,
229 recv_buffer, recv_handle, cp_group, next_rank):
230 """Forward the tail summary before consuming the prepared local chunks."""
231 # These helpers load optional Triton kernels only when the fused path runs.
232 from hyper_parallel.components.functional.gated_delta_net_triton import ( # pylint: disable=import-outside-toplevel
233 chunk_gated_delta_rule_state_summary_fwd,
234 )
235 initial_state = None
236 state_ext = None
237 transition = None
238 if send_next:
239 tail = slice(None) if sequence_info is None else sequence_info.tail
240 state_ext, transition = chunk_gated_delta_rule_state_summary_fwd(
241 key_norm[:, tail], w[:, tail], u[:, tail], g_cumsum[:, tail],
242 output_transition=sequence_info is None or sequence_info.transfer_active,
243 )
244
245 if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active):
246 recv_handle.wait()
247 initial_state = recv_buffer
248 recv_handle = None
249
250 send_buffer = None
251 send_handle = None
252 if send_next:
253 send_buffer = apply_gdn_state_summary(
254 state_ext,
255 transition,
256 initial_state if transition is not None else None,
257 ).contiguous()
258 send_handle = dist.isend(send_buffer, dst=next_rank, group=cp_group)
259
260 if recv_handle is not None:
261 recv_handle.wait()
262 initial_state = recv_buffer
263 return initial_state, transition, send_buffer, send_handle
264
265
266def _finish_gdn_local_backward(ctx, query, key, value, g_cumsum, beta, matrix_a,
267 w, h, v_new, dv, dh, grad_output, cu_seqlens):
268 """Finish local gradients after the outgoing state gradient is in flight."""
269 # These helpers load optional Triton kernels only when the fused path runs.
270 from hyper_parallel.components.functional.gated_delta_net_triton import ( # pylint: disable=import-outside-toplevel
271 chunk_gated_delta_rule_bwd_finish_saved,
272 )
273 empty = query.new_empty(0)
274 dq, dk, dv, dg, dbeta = chunk_gated_delta_rule_bwd_finish_saved(
275 query,
276 key,
277 query,
278 key,
279 value,
280 g_cumsum,
281 beta,
282 matrix_a,
283 w,
284 h,
285 v_new,
286 dv,
287 grad_output,
288 dh,
289 empty,
290 empty,
291 ctx.scale,
292 use_qk_l2norm_in_kernel=False,
293 cu_seqlens=cu_seqlens,
294 )
295 return dq, dk, dv, dg, dbeta
296
297
298class _GDNStateP2PTritonFunction(torch.autograd.Function):
299 """Pipeline fused affine GDN states over sequence-sharded CP ranks."""
300
301 @staticmethod
302 def forward( # pylint: disable=arguments-differ,too-many-locals
303 ctx: Any,
304 query: torch.Tensor,
305 key: torch.Tensor,
306 value: torch.Tensor,
307 g: torch.Tensor,
308 beta: torch.Tensor,
309 cp_rank: int,
310 cp_size: int,
311 cp_group: dist.ProcessGroup,
312 prev_rank: int,
313 next_rank: int,
314 sequence_info: Optional[PackedSequenceInfo],
315 ) -> torch.Tensor:
316 """Run fused local GDN and forward its affine state across CP ranks.
317
318 Args:
319 ctx: Autograd context owning tensors and communication metadata for this invocation.
320 query: Query tensor in batch, token, head, key-dimension order.
321 key: Key tensor with the same token and key-head axes as query.
322 value: Value tensor in batch, token, head, value-dimension order.
323 g: Log decay values for the recurrence.
324 beta: Delta-rule update strengths, or logits when sigmoid fusion is enabled.
325 cp_rank: Rank index within the CP mesh.
326 cp_size: Number of ranks in the CP mesh.
327 cp_group: Process group in sequence-rank order.
328 prev_rank: Global rank sending the incoming state.
329 next_rank: Global rank receiving the outgoing state.
330 sequence_info: Immutable document metadata for this local token interval.
331 """
332 # Optional Triton kernels must stay unloaded for ordinary CPU imports.
333 from hyper_parallel.components.functional.gated_delta_net_triton import ( # pylint: disable=import-outside-toplevel
334 chunk_gated_delta_rule_fwd_apply_state_saved, chunk_gated_delta_rule_fwd_output_saved,
335 chunk_gated_delta_rule_fwd_prepare_saved,
336 )
337
338 receive_previous = cp_rank > 0 and (sequence_info is None or sequence_info.continues_previous)
339 send_next = cp_rank < cp_size - 1 and (sequence_info is None or sequence_info.continues_next)
340 initial_state = None
341 recv_buffer = None
342 recv_handle = None
343 if receive_previous:
344 recv_buffer = torch.empty(
345 (query.shape[0], query.shape[2], query.shape[3], value.shape[3]),
346 device=query.device,
347 dtype=torch.float32,
348 )
349 recv_handle = dist.irecv(recv_buffer, src=prev_rank, group=cp_group)
350
351 cu_seqlens = None if sequence_info is None else sequence_info.materialize(query.device, 64).cu_seqlens
352 (
353 query_norm, key_norm, _, _, g_cumsum, matrix_a, w, u, scale,
354 ) = chunk_gated_delta_rule_fwd_prepare_saved(
355 query, key, value, g, beta,
356 use_qk_l2norm_in_kernel=False,
357 cu_seqlens=cu_seqlens,
358 )
359
360 initial_state, transition, send_buffer, send_handle = _prepare_gdn_forward_send(
361 key_norm, w, u, g_cumsum, send_next, sequence_info,
362 recv_buffer, recv_handle, cp_group, next_rank,
363 )
364 h, v_new, _ = chunk_gated_delta_rule_fwd_apply_state_saved(
365 key_norm, g_cumsum, w, u,
366 initial_state=initial_state if sequence_info is None else sequence_info.first_state(initial_state),
367 output_final_state=False,
368 cu_seqlens=cu_seqlens,
369 )
370 output = chunk_gated_delta_rule_fwd_output_saved(
371 query_norm, key_norm, g_cumsum, h, v_new, scale,
372 cu_seqlens=cu_seqlens,
373 ).to(query.dtype)
374
375 if send_handle is not None:
376 send_handle.wait()
377 del send_buffer
378
379 empty = query.new_empty(0)
380 ctx.save_for_backward(
381 query_norm,
382 key_norm,
383 value,
384 g_cumsum,
385 beta,
386 matrix_a,
387 initial_state if initial_state is not None else empty,
388 transition if transition is not None else empty,
389 cu_seqlens if cu_seqlens is not None else query.new_empty(0, dtype=torch.int64),
390 )
391 ctx.sequence_info = sequence_info
392 ctx.has_initial_state = initial_state is not None
393 ctx.has_transition = transition is not None
394 ctx.receive_previous = receive_previous
395 ctx.send_next = send_next
396 ctx.cp_rank = cp_rank
397 ctx.cp_size = cp_size
398 ctx.cp_group = cp_group
399 ctx.prev_rank = prev_rank
400 ctx.next_rank = next_rank
401 ctx.scale = scale
402 return output
403
404 @staticmethod
405 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple: # pylint: disable=too-many-locals
406 """Backpropagate local GDN tensors and the state gradient wavefront.
407
408 Args:
409 ctx: Autograd context owning tensors and communication metadata for this invocation.
410 grad_output: Gradient of the local operator output.
411 """
412 # Optional Triton kernels must stay unloaded for ordinary CPU imports.
413 from hyper_parallel.components.functional.gated_delta_net_triton import ( # pylint: disable=import-outside-toplevel
414 chunk_gated_delta_rule_bwd_prepare_saved, chunk_gated_delta_rule_bwd_state_saved,
415 )
416 from hyper_parallel.components.functional.gated_delta_net_triton import ( # pylint: disable=import-outside-toplevel
417 chunk_gated_delta_rule_state_gradient_summary_bwd,
418 )
419
420 (
421 query,
422 key,
423 value,
424 g_cumsum,
425 beta,
426 matrix_a,
427 initial_state,
428 transition,
429 saved_cu_seqlens,
430 ) = ctx.saved_tensors
431 sequence_info = ctx.sequence_info
432 cu_seqlens = None if sequence_info is None else saved_cu_seqlens
433 if not ctx.has_initial_state:
434 initial_state = None
435
436 grad_final_state = None
437 recv_handle = None
438 if ctx.send_next:
439 recv_buffer = torch.empty(
440 (query.shape[0], query.shape[2], query.shape[3], value.shape[3]),
441 device=grad_output.device,
442 dtype=torch.float32,
443 )
444 recv_handle = dist.irecv(
445 recv_buffer,
446 src=ctx.next_rank,
447 group=ctx.cp_group,
448 )
449
450 kernel_initial = initial_state if sequence_info is None else sequence_info.first_state(initial_state)
451 w, h, v_new, dv = chunk_gated_delta_rule_bwd_prepare_saved(
452 query,
453 key,
454 value,
455 g_cumsum,
456 beta,
457 matrix_a,
458 kernel_initial,
459 grad_output,
460 ctx.scale,
461 cu_seqlens=cu_seqlens,
462 )
463
464 grad_state_ext = None
465 if ctx.receive_previous:
466 head = slice(None) if sequence_info is None else sequence_info.head
467 grad_state_ext = chunk_gated_delta_rule_state_gradient_summary_bwd(
468 query[:, head], key[:, head], w[:, head], g_cumsum[:, head],
469 grad_output[:, head], dv[:, head], ctx.scale)
470
471 if recv_handle is not None and (sequence_info is None or sequence_info.transfer_active):
472 recv_handle.wait()
473 grad_final_state = recv_buffer
474 recv_handle = None
475
476 send_buffer = None
477 send_handle = None
478 if ctx.receive_previous:
479 send_buffer = apply_gdn_state_gradient_summary(
480 grad_state_ext,
481 transition,
482 grad_final_state if ctx.has_transition else None,
483 ).contiguous()
484 send_handle = dist.isend(
485 send_buffer,
486 dst=ctx.prev_rank,
487 group=ctx.cp_group,
488 )
489
490 if recv_handle is not None:
491 recv_handle.wait()
492 grad_final_state = recv_buffer
493 kernel_grad_final = grad_final_state if sequence_info is None else sequence_info.last_state(grad_final_state)
494 # Rebind dv here so the prepared local gradient is released before finalize.
495 dh, _, dv = chunk_gated_delta_rule_bwd_state_saved(
496 query, key, g_cumsum, w, kernel_initial, kernel_grad_final,
497 grad_output, dv, ctx.scale, cu_seqlens=cu_seqlens,
498 )
499 dq, dk, dv, dg, dbeta = _finish_gdn_local_backward(
500 ctx, query, key, value, g_cumsum, beta, matrix_a,
501 w, h, v_new, dv, dh, grad_output, cu_seqlens,
502 )
503
504 if send_handle is not None:
505 send_handle.wait()
506 return dq, dk, dv, dg, dbeta, None, None, None, None, None, None
507
508
509def triton_state_gdn(
510 query: torch.Tensor,
511 key: torch.Tensor,
512 value: torch.Tensor,
513 g: torch.Tensor,
514 beta: torch.Tensor,
515 cp_mesh: DeviceMesh,
516 cp_rank: int,
517 cp_size: int,
518 sequence_info: Optional[PackedSequenceInfo] = None,
519) -> torch.Tensor:
520 """Run local Triton GDN with an affine state wavefront.
521
522 Args:
523 query: Queries before paired L2 normalization.
524 key: Keys before paired L2 normalization.
525 value: Token-major values.
526 g: FP32 log-decay gates.
527 beta: Activated update weights.
528 cp_mesh: Chronological state communication mesh.
529 cp_rank: Local rank in that mesh.
530 cp_size: Number of state ranks.
531 sequence_info: Immutable local document interval, or None for dense input.
532 """
533 if cp_size == 1:
534 output, _ = chunk_gated_delta_rule(
535 query,
536 key,
537 value,
538 g=g,
539 beta=beta,
540 output_final_state=False,
541 use_qk_l2norm_in_kernel=True,
542 backend="triton",
543 cu_seqlens=None if sequence_info is None else sequence_info.materialize(query.device, 64).cu_seqlens,
544 )
545 return output
546
547 query = _l2norm_torch(query)
548 key = _l2norm_torch(key)
549 prev_rank = _global_peer_rank(cp_mesh, cp_rank - 1) if cp_rank > 0 else -1
550 next_rank = (
551 _global_peer_rank(cp_mesh, cp_rank + 1) if cp_rank < cp_size - 1 else -1
552 )
553 return _GDNStateP2PTritonFunction.apply(
554 query,
555 key,
556 value,
557 g,
558 beta,
559 cp_rank,
560 cp_size,
561 cp_mesh.get_group(),
562 prev_rank,
563 next_rank,
564 sequence_info,
565 )
566
567
568class _AscendCGDNState(torch.autograd.Function):
569 """Keep local activations and asynchronous send storage owned by one invocation."""
570
571 @staticmethod
572 def forward(ctx: Any, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
573 gate: torch.Tensor, beta: torch.Tensor, metadata: dict,
574 exchange: NativeStateExchange) -> torch.Tensor:
575 """Exchange the entry state, then run and save the local native forward."""
576 ops = load_gdn_native_state_ops()
577 reception = exchange.receive(query, True)
578 prepared = prepare_gdn_native((query, key, value, gate, beta), metadata)
579 tail, head, prefix, suffix = native_state_intervals(
580 exchange.info, exchange.local_length, exchange.rank, exchange.size)
581 if exchange.batch_size > 1:
582 tail = head = metadata["cu_seqlens"]
583 maps = None
584 if exchange.needs_summary(True):
585 # GDN local phases use natural log. Native summary kernels use log2.
586 maps = ops.pre_process_fwd_kernel_merged(
587 prepared.key, prepared.weights, prepared.updates,
588 g=prepared.gate * LOG2_E, cu_seqlens=tail, chunk_size=64)
589 initial, send_handle, payloads = exchange.exchange(ops, maps, reception, True, prefix)
590 del maps, reception
591 if exchange.info is not None:
592 initial = exchange.info.first_state(initial)
593 output, hidden, values = finish_gdn_native_forward(prepared, initial, metadata)
594 prepared = prepared._replace(updates=None)
595 ctx.save_for_backward(*prepared, hidden, values)
596 ctx.exchange, ctx.native_metadata, ctx.head, ctx.suffix = exchange, metadata, head, suffix
597 if send_handle is not None:
598 send_handle.wait()
599 del payloads
600 return output
601
602 @staticmethod
603 @once_differentiable
604 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
605 """Exchange the exit-state gradient before completing local native gradients."""
606 ops = load_gdn_native_state_ops()
607 # Unpack once: non-reentrant checkpoint consumes each saved-tensor handle.
608 saved = ctx.saved_tensors
609 prepared = GDNNativePrepared(*saved[:11])
610 hidden, values = saved[11:]
611 exchange, metadata = ctx.exchange, ctx.native_metadata
612 reception = exchange.receive(prepared.query, False)
613 grad = grad_output.transpose(1, 2).contiguous()
614 scale = prepared.key.shape[-1] ** -0.5
615 dv_local = ops.chunk_bwd_dv_local(
616 prepared.query, prepared.key, grad, prepared.gate, scale, 64,
617 A=prepared.matrix_a, **metadata)
618 maps = None
619 if exchange.needs_summary(False):
620 summary_gate = prepared.gate * LOG2_E
621 # Each backward call summarizes one packed sample without copying tokens.
622 summaries = [ops.pre_process_bwd_kernel_merged(
623 prepared.query, prepared.key, prepared.weights, grad, dv_local, scale, 64,
624 g=summary_gate, cu_seqlens=ctx.head[index:index + 2])
625 for index in range(len(ctx.head) - 1)]
626 maps = summaries[0] if len(summaries) == 1 else torch.stack(summaries)
627 del summaries, summary_gate
628 terminal, send_handle, payloads = exchange.exchange(ops, maps, reception, False, ctx.suffix)
629 del maps, reception
630 if exchange.info is not None:
631 terminal = exchange.info.last_state(terminal)
632 dh, _, du = ops.chunk_gated_delta_rule_bwd_dhu(
633 prepared.query, prepared.key, prepared.weights, grad, dv_local, scale, 64,
634 g=prepared.gate, dht=None if terminal is None else terminal.to(prepared.query.dtype),
635 use_exp2=False, **metadata)
636 del dv_local, terminal
637 value = (prepared.value_head if prepared.value_token is None else
638 prepared.value_token.transpose(1, 2).contiguous())
639 dq, dk, dv, dbeta, dgate = ops.chunk_gated_delta_rule_bwd_finalize(
640 prepared.query, prepared.key, value, values, grad, du,
641 prepared.gate, prepared.beta, hidden, dh, prepared.matrix_a,
642 q_rstd=prepared.q_rstd, k_rstd=prepared.k_rstd, scale=scale,
643 use_qk_l2_norm_in_kernel=True, use_exp2=False, **metadata)
644 gradients = tuple(tensor.transpose(1, 2).contiguous() for tensor in (dq, dk, dv, dgate, dbeta))
645 if send_handle is not None:
646 send_handle.wait()
647 del payloads
648 return (*gradients, None, None)
649
650
651def ascendc_state_gdn(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
652 gate: torch.Tensor, beta: torch.Tensor, *, cp_mesh: Any,
653 state_cp: Any = None, sequence_info: Any = None,
654 p2p_head_chunks: int = 1, reuse_cp_state_on_recompute: bool = False,
655 cache_key: object = None) -> torch.Tensor:
656 """Execute dense/TND GDN P2P or AllGather with compact native GVA.
657
658 Args:
659 query: Raw BF16 queries [B,T,Hq,128], normalized inside native Prepare.
660 key: Matching compact keys, with Hv a multiple of Hq.
661 value: BF16 values [B,T,Hv,128].
662 gate: Effective log-decay [B,T,Hv], before chunk cumsum.
663 beta: Effective delta coefficients [B,T,Hv].
664 cp_mesh: Existing chronological state CP mesh.
665 state_cp: Gather executor, or None for ordinary P2P.
666 sequence_info: Real packed document metadata for this rank.
667 p2p_head_chunks: State packets; local Prepare and summary kernels stay unsplit.
668 reuse_cp_state_on_recompute: Reuse this forward entry during a HyperParallel checkpoint replay.
669 cache_key: Stable caller identity; direct callers otherwise follow invocation order.
670
671 Returns:
672 Token-major output. State communication and apply use FP32; only the
673 native Dhu boundary converts the terminal gradient to the input dtype.
674 """
675 if query.device.type != "npu" or query.dtype != torch.bfloat16:
676 raise ValueError("Native GDN state CP requires BF16 NPU inputs.")
677 if query.ndim != 4 or query.shape[0] < 1 or query.shape[-1] != 128 or value.shape[-1] != 128:
678 raise ValueError("Native GDN state CP requires [B,T,H,128] inputs.")
679 if sequence_info is not None and query.shape[0] != 1:
680 raise ValueError("Packed native GDN state CP requires physical batch size one.")
681 if (key.shape != query.shape or value.shape[:2] != query.shape[:2]
682 or value.shape[2] % query.shape[2] or gate.shape != value.shape[:-1] or beta.shape != gate.shape):
683 raise ValueError("Native GDN state CP requires matching Q/K and Hv divisible by Hq, with gates [B,T,Hv].")
684 load_gdn_native_state_ops()
685 batch, tokens = query.shape[:2]
686 offsets = None if sequence_info is None else sequence_info.local_offsets
687 if batch > 1:
688 offsets = tuple(index * tokens for index in range(batch + 1))
689 metadata = local_chunk_metadata(offsets, batch * tokens)
690 exchange = NativeStateExchange(cp_mesh, state_cp, sequence_info, tokens, value.shape[2],
691 p2p_head_chunks, reuse_cp_state_on_recompute=reuse_cp_state_on_recompute,
692 cache_key=cache_key, algorithm="gdn", batch_size=batch)
693 inputs = tuple(tensor.reshape(1, batch * tokens, *tensor.shape[2:])
694 for tensor in (query, key, value, gate, beta))
695 output = _AscendCGDNState.apply(*inputs, metadata, exchange)
696 return output.reshape_as(value)