Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / gated_delta_net_ascendc.py: 34%
99 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Optional Ascend C GDN core with compact GVA and native norm/sigmoid."""
17from __future__ import annotations
19import importlib
20import inspect
21from collections.abc import Sequence
22from functools import lru_cache
23from typing import Any, NamedTuple
25import torch
26from torch.autograd.function import once_differentiable
28from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import local_chunk_metadata
31@lru_cache(maxsize=1)
32def _load_ops():
33 """Keep the optional native runtime out of ordinary framework imports."""
34 try:
35 ops = importlib.import_module("fla_npu.ops.ascendc")
36 except ImportError as error:
37 raise RuntimeError("GDN backend='ascendc' requires a compatible fla-npu installation.") from error
38 required = {
39 "chunk_gated_delta_rule_fwd": (
40 "layout", "use_exp2", "cu_seqlens", "chunk_indices", "disable_recompute",
41 "use_qk_l2norm_in_kernel", "use_beta_sigmoid_in_kernel", "use_gate_in_kernel",
42 ),
43 "chunk_gated_delta_rule_bwd": (
44 "layout", "use_exp2", "cu_seqlens", "chunk_indices", "use_qk_l2norm_in_kernel",
45 "use_beta_sigmoid_in_kernel", "use_gate_in_kernel", "q_rstd", "k_rstd", "beta_raw",
46 ),
47 }
48 for name, parameters in required.items():
49 try:
50 signature = inspect.signature(getattr(ops, name, None))
51 except (TypeError, ValueError) as error:
52 raise RuntimeError(f"fla-npu lacks a compatible public {name} API.") from error
53 missing = set(parameters).difference(signature.parameters)
54 if missing:
55 raise RuntimeError(f"fla-npu {name} lacks required parameters {sorted(missing)}.")
56 return ops
59class _AscendCGDN(torch.autograd.Function):
60 """Own each invocation's native backward intermediates independently."""
62 @staticmethod
63 def forward(ctx: Any, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
64 gate: torch.Tensor, beta: torch.Tensor, metadata: dict,
65 normalize_qk: bool, sigmoid_beta: bool) -> torch.Tensor:
66 """Save only the tensors consumed by the native composite backward.
68 Args:
69 ctx: Autograd context owning this invocation's saved tensors.
70 query: Raw queries when normalize_qk is enabled, otherwise effective queries.
71 key: Keys with the same compact head count as query.
72 value: Value tensor in the same dense or packed layout.
73 gate: Effective log-decay before the chunk cumulative sum.
74 beta: Raw logits when sigmoid_beta is enabled, otherwise effective coefficients.
75 metadata: Host document boundaries and chunk indices, or an empty dict.
76 normalize_qk: Normalize compact Q/K and save native backward auxiliaries.
77 sigmoid_beta: Fuse sigmoid and its backward into the native operations.
79 Returns:
80 Attention output in the input layout.
81 """
82 scale = query.shape[-1] ** -0.5
83 layout = "TND" if metadata else "BSND"
84 original_value = value
85 if normalize_qk:
86 # Keep the exported Q/K hats head-major across forward/backward.
87 # Native scalar gates, dO and output remain token-major in this API.
88 layout = "NTD" if metadata else "BNSD"
89 query, key, value = (tensor.transpose(1, 2).contiguous() for tensor in (query, key, value))
90 result = _load_ops().chunk_gated_delta_rule_fwd(
91 query, key, value, gate, beta, scale=scale, layout=layout, chunk_size=64,
92 initial_state=None, output_final_state=False, disable_recompute=True,
93 return_intermediate_states=False, state_v_first=False, use_exp2=False,
94 use_qk_l2norm_in_kernel=normalize_qk, use_beta_sigmoid_in_kernel=sigmoid_beta,
95 use_gate_in_kernel=False, **metadata,
96 )
97 # The ten-slot ABI exports normalized Q/K and rstd only when requested.
98 if len(result) != 10 or any(not isinstance(result[index], torch.Tensor) for index in (0, 2, 3)):
99 raise RuntimeError("fla-npu GDN forward must return ten slots with output, g_cumsum and A tensors.")
100 output, _, gate_cumsum, matrix_a, beta_eff, _, q_hat, k_hat, q_rstd, k_rstd = result
101 if normalize_qk:
102 query, key = q_hat, k_hat
103 # Native beta backward requires beta_raw to match FP32 beta_eff. Keep
104 # the small scalar logits only; raw Q/K need not survive the forward.
105 beta_raw = beta.float() if sigmoid_beta else None
106 if sigmoid_beta:
107 beta = beta_eff
108 # A strided V view may pin the entire packed QKV allocation. Retain
109 # the already converted V then; otherwise reuse the original storage.
110 ctx.value_head_major = normalize_qk and not original_value.is_contiguous()
111 saved_value = value if ctx.value_head_major else original_value
112 ctx.save_for_backward(query, key, saved_value, gate_cumsum, beta, matrix_a, q_rstd, k_rstd, beta_raw)
113 ctx.normalize_qk, ctx.sigmoid_beta = normalize_qk, sigmoid_beta
114 ctx.native_metadata, ctx.layout, ctx.scale = metadata, layout, scale
115 return output
117 @staticmethod
118 @once_differentiable
119 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
120 """Return raw-input gradients, applying enabled native epilogues exactly once.
122 Args:
123 ctx: Context saved by forward for this invocation.
124 grad_output: Gradient of the attention output.
126 Returns:
127 Gradients for query, key, value, gate and beta; None for metadata and flags.
128 """
129 query, key, value, gate_cumsum, beta, matrix_a, q_rstd, k_rstd, beta_raw = ctx.saved_tensors
130 if ctx.normalize_qk and not ctx.value_head_major:
131 value = value.transpose(1, 2).contiguous()
132 gradients = _load_ops().chunk_gated_delta_rule_bwd(
133 query, key, value, gate_cumsum, beta, matrix_a, grad_output.contiguous(), ctx.scale,
134 layout=ctx.layout, chunk_size=64, initial_state=None, dht=None, use_exp2=False,
135 use_qk_l2norm_in_kernel=ctx.normalize_qk, q_rstd=q_rstd, k_rstd=k_rstd,
136 use_beta_sigmoid_in_kernel=ctx.sigmoid_beta, beta_raw=beta_raw,
137 use_gate_in_kernel=False, state_v_first=False, **ctx.native_metadata,
138 )
139 if len(gradients) != 8 or any(not isinstance(gradient, torch.Tensor) for gradient in gradients[:5]):
140 raise RuntimeError("fla-npu GDN backward must return eight slots with all five input gradients.")
141 dq, dk, dv, dbeta, dgate, *_ = gradients
142 if ctx.normalize_qk:
143 dq, dk, dv = (tensor.transpose(1, 2).contiguous() for tensor in (dq, dk, dv))
144 return dq, dk, dv, dgate, dbeta, None, None, None
147def chunk_gated_delta_rule_ascendc(
148 query: torch.Tensor,
149 key: torch.Tensor,
150 value: torch.Tensor,
151 g: torch.Tensor,
152 beta: torch.Tensor,
153 *,
154 use_qk_l2norm_in_kernel: bool = False,
155 use_beta_sigmoid_in_kernel: bool = False,
156 cu_seqlens: torch.Tensor | Sequence[int] | None = None,
157) -> tuple[torch.Tensor, None]:
158 """Run the optional native GDN local core for dense or packed Ulysses.
160 Args:
161 query: Normalized or unnormalized BF16 query of shape [B,T,H,128].
162 key: BF16 key with the same shape as query.
163 value: BF16 values [B,T,HV,128], with HV a positive multiple of H.
164 g: Effective FP32 log-decay of shape [B,T,HV], before chunk cumsum.
165 beta: Delta coefficients or raw sigmoid logits of shape [B,T,HV].
166 use_qk_l2norm_in_kernel: Normalize Q/K in the native prepare stage.
167 use_beta_sigmoid_in_kernel: Apply sigmoid and its derivative inside native operators.
168 cu_seqlens: Immutable document boundaries supplied as host integers.
170 Returns:
171 The output with the same shape as value, and None for final state.
173 Raises:
174 ValueError: Inputs violate the explicit native training contract.
175 RuntimeError: The optional native API or device is unsupported.
176 """
177 if query.ndim != 4:
178 raise ValueError("GDN inputs must have shape [B,T,H,K].")
179 if cu_seqlens is not None and query.shape[0] != 1:
180 raise ValueError("Packed Ascend C GDN requires physical batch size one.")
181 metadata = local_chunk_metadata(cu_seqlens, query.shape[1])
182 return _AscendCGDN.apply(
183 query, key, value, g, beta, metadata, use_qk_l2norm_in_kernel, use_beta_sigmoid_in_kernel), None
186class GDNNativePrepared(NamedTuple):
187 """Head-major recurrence tensors; exactly one V layout survives forward."""
189 value_token: torch.Tensor | None
190 value_head: torch.Tensor | None
191 query: torch.Tensor
192 key: torch.Tensor
193 q_rstd: torch.Tensor
194 k_rstd: torch.Tensor
195 beta: torch.Tensor
196 gate: torch.Tensor
197 weights: torch.Tensor
198 updates: torch.Tensor | None
199 matrix_a: torch.Tensor
202@lru_cache(maxsize=1)
203def load_gdn_native_state_ops() -> Any:
204 """Check public phase capabilities before posting any CP communication."""
205 ops = _load_ops()
206 required = (
207 "chunk_gated_delta_rule_fwd_prepare", "chunk_fwd_h", "chunk_fwd_o",
208 "chunk_bwd_dv_local", "chunk_gated_delta_rule_bwd_dhu", "chunk_gated_delta_rule_bwd_finalize",
209 "pre_process_fwd_kernel_merged", "pre_process_bwd_kernel_merged", "merge_fwd_bwd_kernel",
210 )
211 missing = [name for name in required if not callable(getattr(ops, name, None))]
212 if missing:
213 raise RuntimeError(f"Native GDN state CP requires these fla-npu APIs: {', '.join(missing)}.")
214 return ops
217def prepare_gdn_native(inputs: tuple, metadata: dict) -> GDNNativePrepared:
218 """Convert once and keep compact Q/K and WY in the phase operators' layout.
220 Args:
221 inputs: Token-major raw Q/K, values, effective log-decay and effective beta.
222 metadata: Local real document offsets and their chunk indices.
223 """
224 query, key, value, gate, beta = (tensor.transpose(1, 2).contiguous() for tensor in inputs)
225 prepared = load_gdn_native_state_ops().chunk_gated_delta_rule_fwd_prepare(
226 query, key, value, gate, beta, use_qk_l2norm_in_kernel=True,
227 use_beta_sigmoid_in_kernel=False, use_exp2=False, **metadata)
228 # Avoid pinning a packed QKV parent through a noncontiguous V view.
229 if inputs[2].is_contiguous():
230 return GDNNativePrepared(inputs[2], None, *prepared)
231 return GDNNativePrepared(None, value, *prepared)
234def finish_gdn_native_forward(prepared: GDNNativePrepared, initial: torch.Tensor | None,
235 metadata: dict) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
236 """Consume the true entry and return token-major output plus local backward state.
238 Args:
239 prepared: Head-major local tensors; compact Q/K remain unexpanded.
240 initial: Actual incoming state or None for zero.
241 metadata: Original local document and chunk boundaries.
242 """
243 hidden, values, _ = load_gdn_native_state_ops().chunk_fwd_h(
244 prepared.key, prepared.weights, prepared.updates, g=prepared.gate, initial_state=initial,
245 output_final_state=False, use_exp2=False, **metadata)
246 output = load_gdn_native_state_ops().chunk_fwd_o(
247 prepared.query, prepared.key, values, hidden, prepared.key.shape[-1] ** -0.5,
248 g=prepared.gate, use_exp2=False, output_layout="BNSD", **metadata)
249 return output.transpose(1, 2).contiguous(), hidden, values