Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / dsa_indexer.py: 0%
10 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-10-25 05:45 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-10-25 05:45 +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"""DSA sparse-attention indexer."""
17from typing import Tuple
19import torch # pylint: disable=forbidden-backend-import
20from einops import rearrange
21import omni_training_custom_ops # noqa: F401 # pylint: disable=unused-import
24def dsa_indexer(
25 index_query: torch.Tensor,
26 index_key: torch.Tensor,
27 merge_weight: torch.Tensor,
28 actual_seq_qlen: torch.Tensor,
29 actual_seq_kvlen: torch.Tensor,
30 sparse_count: int,
31) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
32 """Generate top-k token indices for DSA sparse attention.
34 Args:
35 index_query: Indexer query in BSND layout.
36 index_key: Indexer key in BSND layout.
37 merge_weight: Per-head indexer weights in BSN layout.
38 actual_seq_qlen: Cumulative query lengths as an int32 NPU tensor.
39 actual_seq_kvlen: Cumulative key lengths as an int32 NPU tensor.
40 sparse_count: Number of token indices selected for each query.
42 Returns:
43 Top-k indices in ``[T, N_kv, K]`` int32 layout, followed by the query,
44 key, and merge-weight tensors in TND, TND, and TN layouts. Positions
45 without enough causal candidates are filled with ``-1``. The flattened
46 tensors can be passed directly to :func:`dsa_kl_loss`.
47 """
48 index_query_tnd = rearrange(index_query, "b s n d -> (b s) n d")
49 index_key_tnd = rearrange(index_key, "b s n d -> (b s) n d")
50 merge_weight_tnd = rearrange(merge_weight, "b s n -> (b s) n")
51 topk_indices, _ = torch.ops.custom.npu_lightning_indexer_enhance(
52 index_query_tnd,
53 index_key_tnd,
54 merge_weight_tnd,
55 actual_seq_lengths_query=actual_seq_qlen,
56 actual_seq_lengths_key=actual_seq_kvlen,
57 block_table=None,
58 layout_query="TND",
59 layout_key="TND",
60 sparse_count=sparse_count,
61 sparse_mode=3,
62 return_value=False,
63 )
64 return topk_indices, index_query_tnd, index_key_tnd, merge_weight_tnd