Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / dsa_indexer.py: 85%
100 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"""Causal TopK selection for the DeepSeek V4.1 DSA Indexer."""
17from __future__ import annotations
19from functools import partial
20from typing import Protocol
22import torch
24from hyper_parallel.components.functional.dsa_indexer import dsa_indexer as fused_packed_indexer
25from hyper_parallel.components.functional.lightning_indexer import (
26 lightning_indexer, sort_key_indices, validate_indexer_tensors,
27)
29from .._dependency import load_cann, require_package, require_symbol
30from .._dsa_layout import DsaQueryLayout, ReduceSum, packed_segments
31from ..registry import OpRegistry
32from ..spec import OpSpec
35class DsaIndexerFn(Protocol):
36 """Produce sorted causal TopK key IDs with -1 marking unused slots."""
38 def __call__(
39 self, x: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor, *,
40 layout: DsaQueryLayout, sparse_count: int, query_chunk_size: int = 256,
41 reduce_sum: ReduceSum | None = None,
42 ) -> torch.Tensor:
43 """Return int32 key IDs for each query."""
46DSA_INDEXER = OpSpec[DsaIndexerFn](config_key="dsa_indexer", variant="compressed_causal_topk")
49class PackedDsaIndexerFn(Protocol):
50 """Select document-local key IDs and retain the flattened indexer states."""
52 def __call__(
53 self, x: torch.Tensor, key: torch.Tensor, weights: torch.Tensor,
54 query_ends: torch.Tensor, key_ends: torch.Tensor, sparse_count: int,
55 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
56 """Return right-aligned causal TopK with -1 padding, followed by TND states and TN weights."""
59DSA_PACKED_INDEXER = OpSpec[PackedDsaIndexerFn](config_key="dsa_indexer", variant="packed_causal_topk")
62def _native_packed_indexer(
63 x: torch.Tensor, key: torch.Tensor, weights: torch.Tensor,
64 query_ends: torch.Tensor, key_ends: torch.Tensor, sparse_count: int,
65) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
66 """Select causal document-local keys and return flattened indexer inputs."""
67 query, key, weights = (tensor.flatten(0, 1) for tensor in (x, key, weights))
68 indices = []
69 with torch.no_grad(), torch.autocast(device_type=x.device.type, enabled=False):
70 for qs, qe, ks, ke in packed_segments(query_ends, key_ends):
71 keys = key[ks:ke, 0].float()
72 count = min(sparse_count, keys.shape[0])
73 key_pos = torch.arange(keys.shape[0], device=x.device)
74 for start in range(qs, qe, 128):
75 end = min(start + 128, qe)
76 q_pos = torch.arange(start, end, device=x.device) - qe + ke - ks
77 scores = (query[start:end].float() @ keys.T).relu()
78 scores = (scores * weights[start:end].float().unsqueeze(-1)).sum(dim=1)
79 scores = scores.masked_fill(key_pos[None, :] > q_pos[:, None], -torch.inf)
80 values, ids = scores.topk(count, dim=-1)
81 ids = ids.masked_fill(~values.isfinite(), -1).to(torch.int32)
82 indices.append(torch.nn.functional.pad(ids, (0, sparse_count - count), value=-1))
83 return torch.cat(indices).unsqueeze(1), query, key, weights
86def _load_packed_indexer() -> PackedDsaIndexerFn:
87 kernels = require_package("cann_ops_transformer.ops")
88 require_symbol(kernels, "lightning_indexer")
89 require_symbol(kernels, "lightning_indexer_metadata")
90 return fused_packed_indexer
93def _validate_indexer_inputs(
94 query: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor, layout: DsaQueryLayout, chunk_size: int,
95) -> None:
96 """Validate compressed indexer tensor layouts and query chunk size."""
97 compress_ratio = layout.compress_ratio
98 if compress_ratio <= 0:
99 raise ValueError(f"compress_ratio must be positive, got {compress_ratio}")
100 if chunk_size <= 0:
101 raise ValueError(f"query_chunk_size must be positive, got {chunk_size}")
102 if query.ndim != 4:
103 raise ValueError(f"Indexer query must have shape [B, Q, H, D], got {tuple(query.shape)}")
104 batch_size, _, _, head_dim = query.shape
105 if key.ndim != 3 or key.shape[::2] != (batch_size, head_dim):
106 raise ValueError(
107 "compressed index key must have shape [batch, compressed_sequence, head_dim]"
108 )
109 if merge_weight.shape != query.shape[:3]:
110 raise ValueError(
111 f"merge_weight must have shape {tuple(query.shape[:3])}, got {tuple(merge_weight.shape)}"
112 )
113 if layout.minimum_key_indices is not None and layout.minimum_key_indices.shape != query.shape[:2]:
114 raise ValueError("minimum_key_indices must have shape [batch, query]")
117@torch.no_grad()
118def native_dsa_indexer(
119 x: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor, *,
120 layout: DsaQueryLayout, sparse_count: int, query_chunk_size: int = 256,
121 reduce_sum: ReduceSum | None = None,
122) -> torch.Tensor:
123 """Reference ratio-aware causal TopK over a compressed key bank."""
124 query = x
125 _validate_indexer_inputs(query, key, merge_weight, layout, query_chunk_size)
126 batch_size, sequence_length = query.shape[:2]
127 compressed_length = key.shape[1]
128 top_k = min(sparse_count, compressed_length)
129 if top_k <= 0 or sequence_length == 0:
130 return torch.empty(
131 batch_size,
132 sequence_length,
133 max(top_k, 0),
134 dtype=torch.int32,
135 device=query.device,
136 )
138 visible_keys, minimum_key_indices = layout.compressed_bounds(query)
139 key_fp32 = key.float().transpose(1, 2).unsqueeze(1)
140 key_positions = torch.arange(compressed_length, device=query.device).view(1, 1, -1)
141 selected_chunks = []
142 for start in range(0, sequence_length, query_chunk_size):
143 end = min(start + query_chunk_size, sequence_length)
144 # SAC may retain the matmul result; do not mutate its cached tensor.
145 scores = torch.matmul(query[:, start:end].float(), key_fp32).relu()
146 scores = (scores * merge_weight[:, start:end].float().unsqueeze(-1)).sum(dim=2)
147 if reduce_sum is not None:
148 scores = reduce_sum(scores)
149 # Bounds are [1, S]; slice the query axis so the mask covers this chunk.
150 visible = visible_keys[:, start:end].unsqueeze(-1)
151 scores.masked_fill_(key_positions >= visible, float("-inf"))
152 if minimum_key_indices is not None:
153 minimum = minimum_key_indices[:, start:end].unsqueeze(-1)
154 scores.masked_fill_(key_positions < minimum, float("-inf"))
155 top = scores.topk(top_k, dim=-1, sorted=False)
156 indices = top.indices.masked_fill(~torch.isfinite(top.values), compressed_length)
157 indices = sort_key_indices(indices, compressed_length)
158 indices = indices.masked_fill(indices == compressed_length, -1)
159 selected_chunks.append(indices.to(torch.int32))
160 return torch.cat(selected_chunks, dim=1)
163def indexer_native_only(x: torch.Tensor, layout: DsaQueryLayout, reduce_sum: ReduceSum | None) -> str | None:
164 """Explain why the LI V2 candidate cannot represent this call."""
165 if (x.dtype != torch.bfloat16 or x.shape[-1] != 128 or layout.segments is None or reduce_sum is not None):
166 return "LI V2 requires BF16 D=128, document segments and no TP score reduction"
167 return None
170@torch.no_grad()
171def _cann_indexer(
172 x: torch.Tensor, key: torch.Tensor, merge_weight: torch.Tensor, *,
173 layout: DsaQueryLayout, sparse_count: int, query_chunk_size: int = 256,
174 reduce_sum: ReduceSum | None = None,
175) -> torch.Tensor:
176 del reduce_sum
177 _validate_indexer_inputs(x, key, merge_weight, layout, query_chunk_size)
178 validate_indexer_tensors(x, key, merge_weight)
179 return lightning_indexer(x, key, merge_weight, layout.compress_ratio, min(sparse_count, key.shape[1]),
180 layout.segments)
183def register_dsa_indexer(registry: OpRegistry) -> None:
184 """Register the compressed causal TopK contract and its implementations."""
185 registry.register_family("dsa_indexer", specs=(DSA_INDEXER, DSA_PACKED_INDEXER))
186 registry.register_impl(
187 DSA_INDEXER, name="native", devices=("cpu", "cuda", "npu"), load=lambda: native_dsa_indexer,
188 )
189 registry.register_impl(
190 DSA_INDEXER, name="cann", devices=("npu",), load=partial(load_cann, _cann_indexer, "lightning_indexer"),
191 )
192 registry.register_impl(
193 DSA_PACKED_INDEXER, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_packed_indexer,
194 )
195 registry.register_impl(
196 DSA_PACKED_INDEXER, name="cann", devices=("npu",),
197 load=_load_packed_indexer,
198 )