Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / lightning_indexer.py: 79%

101 statements  

« 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"""LightningIndexer V2 adapter for document-local causal TopK selection.""" 

16 

17from __future__ import annotations 

18 

19from functools import lru_cache 

20from typing import Any, Callable 

21 

22import torch 

23 

24from hyper_parallel.components.functional.sparse_flash_mla import csa_tnd_plan 

25 

26 

27# Float32 represents every integer up to this inclusive bound exactly. 

28_FP32_EXACT_INT_LIMIT = 1 << 24 

29 

30 

31def validate_indexer_tensors(query: torch.Tensor, key: torch.Tensor, weights: torch.Tensor) -> None: 

32 """Check logical tensor relationships before packing Indexer or KL inputs. 

33 

34 Native operators validate their hardware-specific dtype and shape limits. 

35 

36 Args: 

37 query: Indexer query [batch, queries, heads, dimension]. 

38 key: Indexer key bank [batch, keys, dimension]. 

39 weights: Per-query head weights [batch, queries, heads]. 

40 

41 Raises: 

42 ValueError: Tensor layouts, devices or query/key dtypes disagree. 

43 """ 

44 if query.ndim != 4: 

45 raise ValueError(f"Indexer query must have shape [B, Q, H, D], got {tuple(query.shape)}") 

46 if key.ndim != 3 or key.shape[::2] != (query.shape[0], query.shape[-1]): 

47 raise ValueError(f"Indexer key must have shape [B, K, D] matching Q, got Q={tuple(query.shape)}, " 

48 f"K={tuple(key.shape)}") 

49 if weights.shape != query.shape[:3]: 

50 raise ValueError(f"Indexer weights must have shape {tuple(query.shape[:3])}, got {tuple(weights.shape)}") 

51 if key.device != query.device or weights.device != query.device: 

52 raise ValueError(f"Indexer Q/K/weights must share a device, got {query.device}, {key.device}, {weights.device}") 

53 if key.dtype != query.dtype: 

54 raise ValueError(f"Indexer Q/K must share a dtype, got {query.dtype} and {key.dtype}") 

55 

56 

57def sort_key_indices(indices: torch.Tensor, maximum: int) -> torch.Tensor: 

58 """Sort key IDs without losing integer precision or changing their dtype. 

59 

60 Args: 

61 indices: Integer key IDs in [-1, maximum], including any sentinel. 

62 maximum: A shape-derived upper bound; does not synchronize the device. 

63 """ 

64 if maximum <= _FP32_EXACT_INT_LIMIT: 

65 return indices.float().sort(dim=-1).values.to(indices.dtype) 

66 return indices.sort(dim=-1).values 

67 

68 

69@lru_cache(maxsize=1) 

70def _load_indexer_op() -> Callable[..., Any]: 

71 """Import the LI V2 entry only when fused selection is requested.""" 

72 # Keep the optional NPU extension out of CPU and eager-only imports. 

73 try: 

74 from cann_ops_transformer import ( # pylint: disable=import-outside-toplevel 

75 lightning_indexer as lightning_indexer_op, 

76 ) 

77 except ImportError as err: 

78 raise RuntimeError( 

79 "use_fused_ops=True requires cann_ops_transformer.lightning_indexer (LI V2). " 

80 "See hyper_parallel/components/functional/README.md for ops-transformer installation, " 

81 "environment setup and tested versions." 

82 ) from err 

83 if callable(lightning_indexer_op): 

84 dispatcher_op = getattr(torch.ops.cann_ops_transformer, "lightning_indexer", None) 

85 if dispatcher_op is not None: 

86 return dispatcher_op 

87 return lightning_indexer_op 

88 

89 

90@lru_cache(maxsize=1) 

91def _load_indexer_metadata_op() -> Callable[..., Any]: 

92 """Import the optional LI scheduling entry only when it will be used.""" 

93 # The verified 910B kernel computes its own split and does not read metadata. 

94 try: 

95 from cann_ops_transformer import lightning_indexer_metadata # pylint: disable=import-outside-toplevel 

96 except ImportError as err: 

97 raise RuntimeError( 

98 "use_fused_ops=True requires cann_ops_transformer.lightning_indexer_metadata on this device. " 

99 "See hyper_parallel/components/functional/README.md for ops-transformer installation, " 

100 "environment setup and tested versions." 

101 ) from err 

102 if callable(lightning_indexer_metadata): 

103 dispatcher_op = getattr(torch.ops.cann_ops_transformer, "lightning_indexer_metadata", None) 

104 if dispatcher_op is not None: 

105 return dispatcher_op 

106 return lightning_indexer_metadata 

107 

108 

109@lru_cache(maxsize=16) 

110def _uses_indexer_metadata(device: torch.device) -> bool: 

111 """Omit unused LI scheduling metadata on the verified 910B path. 

112 

113 LI V2's arch22 kernel computes its split internally; arch35 requires 

114 metadata. Keep the standard metadata call on other devices rather than 

115 assuming they share the verified 910B behavior. TND still needs cu_seqlens. 

116 """ 

117 return "910B" not in torch.npu.get_device_name(device) 

118 

119 

120@lru_cache(maxsize=128) 

121@torch.inference_mode(False) 

122def _bsnd_indexer_metadata(device, batch, length, heads, dim, key_length, topk, ratio, residual): 

123 """Reuse shape-only BSND metadata without caching inference-mode tensors.""" 

124 residue = torch.full((batch,), residual, device=device, dtype=torch.int32) if ratio > 1 else None 

125 metadata = None 

126 if _uses_indexer_metadata(device): 

127 metadata = _load_indexer_metadata_op()( 

128 heads, 1, dim, topk, cmp_residual_k=residue, 

129 batch_size=batch, max_seqlen_q=length, max_seqlen_k=key_length, 

130 layout_q="BSND", layout_k="BSND", mask_mode=3, cmp_ratio=ratio, 

131 ) 

132 return residue, metadata 

133 

134 

135@torch.no_grad() 

136def _bsnd_lightning_indexer( 

137 query: torch.Tensor, key: torch.Tensor, weights: torch.Tensor, ratio: int, topk: int, 

138 segment: tuple[int, int, int, int, int], 

139) -> torch.Tensor: 

140 """Select one document segment per batch item in one BSND call. 

141 

142 Query tiling is owned by the operator, independently of the external 

143 teacher chunk size. Multiple packed documents use the TND entry. 

144 

145 Args: 

146 query: Local Indexer queries [batch, queries, heads, 128]. 

147 key: Global Indexer key bank [batch, compressed keys, 128]. 

148 weights: Local per-head merge weights, including model scaling. 

149 ratio: Model compression ratio. 

150 topk: Output selection width, including invalid tail slots. 

151 segment: Local Q start/end, global compressed K start/end, and raw 

152 prefix length modulo ratio, shared by all physical batch items. 

153 """ 

154 batch, length, heads, dim = query.shape 

155 result = torch.full((batch, length, topk), -1, device=query.device, dtype=torch.int32) 

156 start, end, key_start, key_end, residual = segment 

157 if key_end <= key_start or start == end: 

158 return result 

159 indexer = _load_indexer_op() 

160 residue, metadata = _bsnd_indexer_metadata( 

161 query.device, batch, end-start, heads, dim, key_end-key_start, topk, ratio, residual, 

162 ) 

163 # Rebuild singleton strides; contiguous() alone may retain the full-bank batch stride. 

164 native_key = key[:, key_start:key_end].contiguous().view(batch, key_end-key_start, 1, dim) 

165 with torch.autocast(device_type=query.device.type, enabled=False): 

166 # Singleton batch strides may survive contiguous(); view canonicalizes the native BSND layout. 

167 native_key = key[:, key_start:key_end].contiguous().view(batch, key_end-key_start, 1, dim) 

168 indices, _ = indexer( 

169 query[:, start:end].contiguous(), native_key, 

170 weights[:, start:end].float().contiguous(), topk, 

171 cmp_residual_k=residue, metadata=metadata, 

172 layout_q="BSND", layout_k="BSND", mask_mode=3, cmp_ratio=ratio, 

173 ) 

174 indices = indices[:, :, 0] 

175 indices = torch.where(indices >= 0, indices + key_start, key.shape[1]) 

176 indices = sort_key_indices(indices, key.shape[1]) 

177 result[:, start:end] = indices.masked_fill(indices == key.shape[1], -1) 

178 return result 

179 

180 

181@lru_cache(maxsize=128) 

182@torch.inference_mode(False) 

183def _tnd_indexer_metadata(plan, device, heads, dim, topk, ratio): 

184 """Cache native selection metadata for the complete packed document partition.""" 

185 options = plan.indexer_options(device, ratio) 

186 metadata = None 

187 if _uses_indexer_metadata(device): 

188 metadata = _load_indexer_metadata_op()( 

189 heads, 1, dim, topk, batch_size=len(plan.segments), 

190 max_seqlen_q=max(plan.q_lengths), max_seqlen_k=max(plan.k_lengths), **options, 

191 ) 

192 return options, metadata 

193 

194 

195@torch.no_grad() 

196def lightning_indexer( 

197 query: torch.Tensor, key: torch.Tensor, weights: torch.Tensor, ratio: int, topk: int, segments: tuple, 

198) -> torch.Tensor: 

199 """Select packed document prefixes in one TND call; single documents use BSND. 

200 

201 Args: 

202 query: Local Indexer queries [batch, queries, heads, 128]. 

203 key: Global Indexer key bank [batch, compressed keys, 128]. 

204 weights: Per-query head weights including model scaling. 

205 ratio: Model compression ratio. 

206 topk: Selection width, including invalid tail slots. 

207 segments: Local Q start/end, global document K start/prefix end and 

208 raw-prefix residual. Packed documents require batch size one. 

209 

210 Returns: 

211 Sorted global key IDs [batch, queries, topk], with invalid slots -1. 

212 """ 

213 if len(segments) == 1: 

214 return _bsnd_lightning_indexer(query, key, weights, ratio, topk, segments[0]) 

215 if query.shape[0] != 1: 

216 raise ValueError("Packed Lightning Indexer requires batch size one") 

217 plan = csa_tnd_plan(segments, ratio) 

218 if plan is None: 

219 return torch.full((*query.shape[:2], topk), -1, device=query.device, dtype=torch.int32) 

220 options, metadata = _tnd_indexer_metadata(plan, query.device, query.shape[2], query.shape[3], topk, ratio) 

221 with torch.autocast(device_type=query.device.type, enabled=False): 

222 indices, _ = _load_indexer_op()( 

223 plan.query(query), plan.key(key).unsqueeze(1), plan.query(weights).float(), topk, 

224 metadata=metadata, **options, 

225 ) 

226 offsets = plan.lengths(query.device)[3] 

227 indices = torch.where(indices[:, 0] >= 0, indices[:, 0] + offsets, key.shape[1]) 

228 indices = sort_key_indices(indices, key.shape[1]) 

229 indices = indices.masked_fill(indices == key.shape[1], -1) 

230 if plan.covers_queries(query.shape[1]): 

231 return indices.unsqueeze(0) 

232 result = torch.full((*query.shape[:2], topk), -1, device=query.device, dtype=torch.int32) 

233 plan.restore(indices, result) 

234 return result