Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / __init__.py: 98%
145 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"""OpSelect operator entry points and backend configuration."""
17from __future__ import annotations
19from typing import Any
21import torch
23from hyper_parallel.components.modules.attention.linear_attention_utils.sequence_layout import PackedSequenceInfo
24from hyper_parallel.components.functional.npu_fusion_attention import resolve_packed_sequence_lengths
26from ._dsa_layout import DsaQueryLayout, ReduceSum
27from .factory import _dispatch, _select_for_call, ops
28from .impl.attention import (
29 GROUPED_QUERY_ATTENTION, MULTI_LATENT_ATTENTION, MULTI_LATENT_ATTENTION_WITH_STATS, VISION_ATTENTION,
30 DenseAttentionFn, MultiLatentAttentionStatsFn, VisionAttentionFn,
31)
32from .impl.causal_conv1d import CAUSAL_CONV1D
33from .impl.dsa_indexer import (
34 DSA_INDEXER, DSA_PACKED_INDEXER, PackedDsaIndexerFn, indexer_native_only, native_dsa_indexer,
35)
36from .impl.dsa_indexer_kl import (
37 DSA_DENSE_KL, DSA_INDEXER_KL, DSA_PACKED_KL, DenseDsaKlFn, PackedDsaKlFn, indexer_kl_native_only,
38 native_dsa_indexer_kl,
39)
40from .impl.deepseek_sparse_attention import (
41 DSA_ABSORBED, DSA_ABSORBED_SINK, DSA_COMPRESSED_BANKS, PackedDeepseekSparseAttentionFn, attention_native_only,
42)
43from .impl.gdn import GDN
44from .impl.grouped_matmul import GROUPED_MATMUL, GroupedMatmulFn
45from .impl.grouped_swiglu import GROUPED_SWIGLU
46from .impl.kda import KDA
47from .impl.mhc_post import MHC_POST, MhcPostFn
48from .impl.moe_router import MOE_ROUTER, router_scores
49from .impl.moe_token_reorder import MOE_TOKEN_REORDER, MOE_TOKEN_RESTORE, PermutedTokens
50from .impl.mome import MOME, MomeFn
51from .impl.rms_norm import RMS_NORM, RMS_NORM_FP32_AFFINE, RMSNormFn
52from .impl.rope import ROPE, ROPE_INTERLEAVED, InterleavedRopeFn, RopeFn
53from .impl.sinkhorn import SINKHORN, SinkhornFn
54from .impl.swiglu import SWIGLU, SWIGLU_CLAMPED, ClampedSwiGLUFn, SwiGLUFn
55from .spec import OpSpec
57__all__ = [
58 "DsaQueryLayout", "causal_conv1d", "dsa_indexer", "dsa_indexer_kl", "dsa_indexer_kl_dense",
59 "dsa_indexer_kl_packed", "dsa_indexer_packed",
60 "deepseek_sparse_attention_absorbed", "deepseek_sparse_attention_compressed_banks",
61 "deepseek_sparse_attention_with_sink",
62 "gdn", "grouped_query_attention", "grouped_matmul", "grouped_swiglu", "kda", "mhc_post", "multi_latent_attention",
63 "multi_latent_attention_with_stats",
64 "moe_router", "moe_token_reorder", "moe_token_restore", "mome", "ops", "rms_norm", "rms_norm_fp32_affine",
65 "router_scores",
66 "rope", "rope_interleaved", "rope_qk",
67 "sinkhorn", "swiglu", "swiglu_clamped", "vision_attention",
68]
70grouped_matmul: GroupedMatmulFn = _dispatch(GROUPED_MATMUL)
71dsa_indexer_packed: PackedDsaIndexerFn = _dispatch(DSA_PACKED_INDEXER)
72dsa_indexer_kl_dense: DenseDsaKlFn = _dispatch(DSA_DENSE_KL)
73dsa_indexer_kl_packed: PackedDsaKlFn = _dispatch(DSA_PACKED_KL)
74deepseek_sparse_attention_absorbed: PackedDeepseekSparseAttentionFn = _dispatch(DSA_ABSORBED)
75deepseek_sparse_attention_with_sink: PackedDeepseekSparseAttentionFn = _dispatch(DSA_ABSORBED_SINK)
76mhc_post: MhcPostFn = _dispatch(MHC_POST)
77multi_latent_attention_with_stats: MultiLatentAttentionStatsFn = _dispatch(MULTI_LATENT_ATTENTION_WITH_STATS)
78mome: MomeFn = _dispatch(MOME)
79rms_norm: RMSNormFn = _dispatch(RMS_NORM)
80rms_norm_fp32_affine: RMSNormFn = _dispatch(RMS_NORM_FP32_AFFINE)
81rope: RopeFn = _dispatch(ROPE)
82rope_interleaved: InterleavedRopeFn = _dispatch(ROPE_INTERLEAVED)
83sinkhorn: SinkhornFn = _dispatch(SINKHORN)
84swiglu: SwiGLUFn = _dispatch(SWIGLU)
85swiglu_clamped: ClampedSwiGLUFn = _dispatch(SWIGLU_CLAMPED)
86vision_attention: VisionAttentionFn = _dispatch(VISION_ATTENTION)
89def _dense_mask(mask: torch.Tensor | None, key_length: int, packed: bool) -> torch.Tensor | None:
90 """Normalize key padding and pairwise mask dimensions before dense attention."""
91 if mask is not None and not packed:
92 mask = mask[..., :key_length]
93 if mask is not None and mask.ndim == 3:
94 mask = mask.unsqueeze(1)
95 return mask
98def _dense_window(
99 module: torch.nn.Module, query_length: int, key_length: int, causal: bool, kwargs: dict[str, Any],
100) -> int | None:
101 """Resolve an explicit sliding window or the module's causal token limit."""
102 window = kwargs.get("sliding_window")
103 if window is None and causal and query_length == key_length:
104 pre_tokens = kwargs.get("pre_tokens", getattr(module, "pre_tockens", None))
105 if pre_tokens is not None and pre_tokens < query_length:
106 window = pre_tokens + 1
107 return window
110def _dense_attention(
111 spec: OpSpec[DenseAttentionFn], module: torch.nn.Module, query: torch.Tensor,
112 key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None,
113 dropout: float, scaling: float | None, kwargs: dict[str, Any],
114) -> tuple[torch.Tensor, None]:
115 """Normalize dense attention arguments and dispatch the selected contract."""
116 if kwargs.get("indices") is not None:
117 raise ValueError("Dense attention does not consume sparse attention indices")
118 q_len, k_len = query.shape[2], key.shape[2]
119 q_ends, k_ends = resolve_packed_sequence_lengths(kwargs, query.shape[0] * q_len, key.shape[0] * k_len)
120 lengths = (q_ends, k_ends) if q_ends is not None else None
121 if lengths is not None and len(q_ends) != len(k_ends):
122 raise ValueError("Packed query and key lengths must contain the same number of segments")
123 attention_mask = _dense_mask(attention_mask, k_len, lengths is not None)
124 causal = kwargs.get("is_causal", getattr(module, "is_causal", True))
125 if q_len != k_len and attention_mask is not None and attention_mask.ndim >= 3 and lengths is None:
126 # CP masks already encode the query's global offset.
127 causal = False
128 window = _dense_window(module, q_len, k_len, causal, kwargs)
129 query_offset = kwargs.get("query_offset")
130 blocked = ()
131 if lengths is not None and attention_mask is not None:
132 blocked = (("torch_npu", "packed attention requires segment boundaries without an external mask"),)
133 operation = _select_for_call(spec, query, blocked_backends=blocked)
134 scale = query.shape[-1] ** -0.5 if scaling is None else scaling
135 return operation(
136 query, key, value, attention_mask, causal=causal, scale=scale, dropout=dropout,
137 window=window, lengths=lengths, query_offset=query_offset,
138 ), None
141def grouped_query_attention(
142 module: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
143 attention_mask: torch.Tensor | None, dropout: float = 0.0, scaling: float | None = None, **kwargs: Any,
144) -> tuple[torch.Tensor, None]:
145 """Run the dense grouped-query contract through a Transformers-compatible entry point."""
146 return _dense_attention(
147 GROUPED_QUERY_ATTENTION, module, query, key, value, attention_mask, dropout, scaling, kwargs,
148 )
151def multi_latent_attention(
152 module: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
153 attention_mask: torch.Tensor | None, dropout: float = 0.0, scaling: float | None = None, **kwargs: Any,
154) -> tuple[torch.Tensor, None]:
155 """Attend over projected MLA states, allowing the value dimension to differ from Q and K."""
156 return _dense_attention(MULTI_LATENT_ATTENTION, module, query, key, value, attention_mask, dropout, scaling, kwargs)
159def rope_qk(
160 query: torch.Tensor, key: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, *, unsqueeze_dim: int = 1,
161) -> tuple[torch.Tensor, torch.Tensor]:
162 """Apply half-layout RoPE on Q and K with Transformers position embeddings."""
163 if cos.ndim == 2:
164 cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
165 if cos.shape[0] == 1 and query.shape[0] > 1:
166 cos = cos.expand(query.shape[0], -1, -1)
167 sin = sin.expand(query.shape[0], -1, -1)
168 cos, sin = cos.unsqueeze(unsqueeze_dim), sin.unsqueeze(unsqueeze_dim)
169 return rope(query, cos, sin), rope(key, cos, sin)
172_LINEAR_ATTENTION_BACKENDS = {"eager": "native", "triton": "triton_ascend"}
175def grouped_swiglu(
176 x: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor, w3: torch.Tensor, counts: torch.Tensor,
177 scores: torch.Tensor | None = None, *, backend: str = "auto",
178) -> torch.Tensor:
179 """Apply grouped expert SwiGLU after resolving the family backend."""
180 operation = _select_for_call(GROUPED_SWIGLU, x, default_backend=backend)
181 return operation(x, w1, w2, w3, counts, scores)
184def causal_conv1d(
185 x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None, info: PackedSequenceInfo | None = None,
186 *, dilation: int = 1, backend: str = "auto",
187) -> torch.Tensor:
188 """Apply local depthwise causal convolution and SiLU to dense or packed tokens."""
189 reason = "fused convolution requires nonempty batches and dilation one" if dilation != 1 or not x.numel() else None
190 blocked = ()
191 if (
192 weight.shape[-1] not in (2, 3, 4) or x.shape[-1] % 16 or x.dtype not in (torch.bfloat16, torch.float16)
193 or weight.dtype != x.dtype or (bias is not None and bias.dtype != x.dtype)
194 ):
195 blocked = (("ascendc", "requires width 2/3/4, 16-aligned channels and matching BF16/FP16 dtypes"),)
196 operation = _select_for_call(
197 CAUSAL_CONV1D, x, native_only=reason, blocked_backends=blocked,
198 default_backend=_LINEAR_ATTENTION_BACKENDS.get(backend, backend),
199 )
200 return operation(x, weight, bias, info, dilation=dilation)
203def gdn(
204 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor,
205 *, chunk_size: int = 64, normalize_qk: bool = True, info: PackedSequenceInfo | None = None,
206 backend: str = "auto",
207) -> torch.Tensor:
208 """Compute zero-state GDN with effective gate and beta inputs."""
209 reason = None
210 if (
211 chunk_size != 64 or x.shape[-1] != 128 or value.shape[-1] != 128
212 or x.dtype != torch.bfloat16 or key.dtype != x.dtype or value.dtype != x.dtype
213 or beta.dtype != x.dtype or gate.dtype != torch.float32
214 ):
215 reason = "fused GDN requires chunk size 64, head dimension 128, BF16 Q/K/V/beta and FP32 gate"
216 operation = _select_for_call(
217 GDN, x, native_only=reason, default_backend=_LINEAR_ATTENTION_BACKENDS.get(backend, backend),
218 )
219 return operation(x, key, value, gate, beta, chunk_size=chunk_size, normalize_qk=normalize_qk, info=info)
222def kda(
223 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor,
224 *, a_log: torch.Tensor, dt_bias: torch.Tensor, lower_bound: float | None, chunk_size: int = 64,
225 scale: float | None = None, info: PackedSequenceInfo | None = None, backend: str = "auto",
226) -> torch.Tensor:
227 """Compute zero-state KDA with raw gate and beta logits."""
228 reason = None
229 if (
230 lower_bound is None or not -5.0 <= lower_bound < 0 or chunk_size != 64
231 or x.shape[-1] != 128 or value.shape[-1] != 128
232 or x.dtype != torch.bfloat16 or key.dtype != x.dtype or value.dtype != x.dtype
233 ):
234 reason = "fused KDA requires a safe gate, chunk size 64, head dimension 128 and BF16 Q/K/V"
235 blocked = []
236 if gate.dtype != x.dtype or beta.dtype != x.dtype:
237 blocked.append(("triton_ascend", "requires BF16 gate and beta"))
238 if x.shape[2] != value.shape[2]:
239 blocked.append(("ascendc", "requires matching Q/K/V head counts"))
240 operation = _select_for_call(
241 KDA, x, native_only=reason, blocked_backends=tuple(blocked),
242 default_backend=_LINEAR_ATTENTION_BACKENDS.get(backend, backend),
243 )
244 return operation(x, key, value, gate, beta, a_log=a_log, dt_bias=dt_bias, lower_bound=lower_bound,
245 chunk_size=chunk_size, scale=scale, info=info)
248def dsa_indexer(
249 x: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor, *,
250 layout: DsaQueryLayout, sparse_count: int, query_chunk_size: int = 256,
251 reduce_sum: ReduceSum | None = None,
252) -> torch.Tensor:
253 """Select causal compressed keys and return sorted int32 IDs."""
254 if x.ndim != 4 or key.ndim != 3 or min(sparse_count, key.shape[1]) <= 0 or x.shape[1] == 0:
255 implementation = native_dsa_indexer
256 else:
257 implementation = _select_for_call(DSA_INDEXER, x, native_only=indexer_native_only(x, layout, reduce_sum))
258 return implementation(
259 x, key, merge_weight, layout=layout, sparse_count=sparse_count,
260 query_chunk_size=query_chunk_size, reduce_sum=reduce_sum,
261 )
264def dsa_indexer_kl(
265 x: torch.Tensor, index_key: torch.Tensor, merge_weight: torch.Tensor,
266 attention_query: torch.Tensor, compressed_key: torch.Tensor, topk_indices: torch.Tensor,
267 sinks: torch.Tensor, *, attention_scale: float, loss_coeff: float, query_chunk_size: int = 256,
268 reduce_sum: ReduceSum | None = None, layout: DsaQueryLayout | None = None,
269) -> torch.Tensor:
270 """Compute the scalar Indexer KL loss, with gradients restricted to the student."""
271 if not loss_coeff or index_key.shape[1] == 0 or x.shape[1] == 0:
272 implementation = native_dsa_indexer_kl
273 else:
274 reason = indexer_kl_native_only(x, index_key, topk_indices, layout, reduce_sum)
275 implementation = _select_for_call(DSA_INDEXER_KL, x, native_only=reason)
276 return implementation(
277 x, index_key, merge_weight, attention_query, compressed_key, topk_indices, sinks,
278 attention_scale=attention_scale, loss_coeff=loss_coeff, query_chunk_size=query_chunk_size,
279 reduce_sum=reduce_sum, layout=layout,
280 )
283def deepseek_sparse_attention_compressed_banks(
284 x: torch.Tensor, raw_key: torch.Tensor, compressed_key: torch.Tensor | None,
285 topk_indices: torch.Tensor | None, sinks: torch.Tensor, *, scale: float, window: int,
286 layout: DsaQueryLayout, global_sequence_length: int, raw_key_offset: int = 0,
287 main_key_offset: int = 0, global_key_length: int | None = None,
288) -> torch.Tensor:
289 """Attend a sliding window and optional compressed keys in logical document coordinates."""
290 reason = attention_native_only(x, layout, window, topk_indices, global_sequence_length, global_key_length)
291 implementation = _select_for_call(DSA_COMPRESSED_BANKS, x, native_only=reason)
292 return implementation(
293 x, raw_key, compressed_key, topk_indices, sinks, scale=scale, window=window,
294 layout=layout, global_sequence_length=global_sequence_length,
295 raw_key_offset=raw_key_offset, main_key_offset=main_key_offset, global_key_length=global_key_length,
296 )
299def moe_token_reorder(x: torch.Tensor, indices: torch.Tensor) -> PermutedTokens:
300 """Arrange routed slots for expert execution with the selected permutation pair."""
301 reason = "fused permutation requires at least one routed slot" if indices.numel() == 0 else None
302 return _select_for_call(MOE_TOKEN_REORDER, x, native_only=reason)(x, indices)
305def moe_token_restore(x: torch.Tensor, slot_positions: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
306 """Reduce weighted expert outputs in the original token order."""
307 reason = "fused restoration requires at least one routed slot" if slot_positions.numel() == 0 else None
308 return _select_for_call(MOE_TOKEN_RESTORE, x, native_only=reason)(x, slot_positions, weights)
311def _check_native_ep_reorder(x: torch.Tensor) -> None:
312 """Check the configured backend before using EP's chunked or compact dispatch."""
313 _select_for_call(
314 MOE_TOKEN_REORDER, x, native_only="fused permutation requires full, unchunked routing without a capacity limit",
315 )
318def moe_router(
319 x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, vision_bias: torch.Tensor | None,
320 image_mask: torch.Tensor | None, top_k: int, scoring_func: str, scale: float,
321) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
322 """Compute logits, routing weights and expert IDs for DeepSeek's top-k router."""
323 native_only = None
324 if scoring_func != "sqrtsoftplus" or x.ndim != 3 or x.numel() == 0:
325 native_only = "MegaGate requires nonempty batched tokens and sqrtsoftplus scoring"
326 route = _select_for_call(MOE_ROUTER, x, native_only=native_only)
327 return route(x, weight, bias, vision_bias, image_mask, top_k, scoring_func, scale)