Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / impl / deepseek_sparse_attention.py: 83%

134 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"""Attention over raw and compressed KV banks in DeepSeek V4.1.""" 

16 

17from __future__ import annotations 

18 

19from functools import partial 

20from typing import Protocol 

21 

22import torch 

23from torch.nn import functional as F 

24 

25from hyper_parallel.components.functional.dsa_sparse_attention import dsa_sparse_attention as fused_packed_attention 

26from hyper_parallel.components.functional.sparse_flash_mla import sparse_flash_mla, supports_fused_attention_inputs 

27 

28from .._dependency import load_cann, require_package, require_symbol 

29from .._dsa_layout import DsaQueryLayout, packed_segments, selected_packed_keys, selected_packed_scores 

30from ..registry import OpRegistry 

31from ..spec import OpSpec 

32 

33 

34class DsaCompressedBanksFn(Protocol): 

35 """Attend raw and compressed KV banks in the same document coordinates.""" 

36 

37 def __call__( 

38 self, x: torch.Tensor, raw_key: torch.Tensor, compressed_key: torch.Tensor | None, 

39 topk_indices: torch.Tensor | None, sinks: torch.Tensor, *, scale: float, window: int, 

40 layout: DsaQueryLayout, global_sequence_length: int, raw_key_offset: int = 0, 

41 main_key_offset: int = 0, global_key_length: int | None = None, 

42 ) -> torch.Tensor: 

43 """Return attention output in BSND layout.""" 

44 

45 

46DSA_COMPRESSED_BANKS = OpSpec[DsaCompressedBanksFn](config_key="deepseek_sparse_attention", variant="compressed_banks") 

47 

48 

49class PackedDeepseekSparseAttentionFn(Protocol): 

50 """Attend packed, absorbed MLA states and expose per-head sparse softmax statistics.""" 

51 

52 def __call__( 

53 self, x: torch.Tensor, key: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor, 

54 topk_indices: torch.Tensor, scale: float, query_ends: torch.Tensor, key_ends: torch.Tensor, 

55 *, sink_key: torch.Tensor | None = None, sink_value: torch.Tensor | None = None, dropout: float = 0.0, 

56 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

57 """Return padded BSND output and sparse max/sum in KV-head, token, group layout.""" 

58 

59 

60DSA_ABSORBED = OpSpec[PackedDeepseekSparseAttentionFn]( 

61 config_key="deepseek_sparse_attention", variant="absorbed_with_stats", 

62) 

63DSA_ABSORBED_SINK = OpSpec[PackedDeepseekSparseAttentionFn]( 

64 config_key="deepseek_sparse_attention", variant="absorbed_with_parameter_sink", 

65) 

66 

67 

68def _native_absorbed( 

69 x: torch.Tensor, key: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor, 

70 topk_indices: torch.Tensor, scale: float, query_ends: torch.Tensor, key_ends: torch.Tensor, 

71 *, sink_key: torch.Tensor | None = None, sink_value: torch.Tensor | None = None, dropout: float = 0.0, 

72) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

73 # Accumulate shared KV gradients in FP32 before casting back to input dtype; 

74 # casting after gathering rounds contributions from each sparse slot first. 

75 """Compute packed sparse MLA outputs and detached teacher statistics.""" 

76 query, value, q_rope, k_rope = (tensor.flatten(0, 1).float() for tensor in (x, key, query_rope, key_rope)) 

77 outputs, maxima, totals = [], [], [] 

78 with torch.autocast(device_type=x.device.type, enabled=False): 

79 for qs, qe, ks, ke in packed_segments(query_ends, key_ends): 

80 for start in range(qs, qe, 32): 

81 end = min(start + 32, qe) 

82 indices = topk_indices[start:end] 

83 causal = torch.arange(start, end, device=x.device) - qe + ke - ks 

84 selected, valid = selected_packed_keys(value[ks:ke], indices, causal_end=causal) 

85 rotary_keys, _ = selected_packed_keys(k_rope[ks:ke], indices, causal_end=causal) 

86 scores = (selected_packed_scores(query[start:end], selected) 

87 + selected_packed_scores(q_rope[start:end], rotary_keys)) * scale 

88 scores = scores.masked_fill(~valid.unsqueeze(2), -torch.inf) 

89 maximum = scores.amax(dim=-1, keepdim=True) 

90 maximum = torch.where(maximum.isfinite(), maximum, 0.0) 

91 exp = (scores - maximum).exp() 

92 total = exp.sum(dim=-1, keepdim=True) 

93 if sink_key is None: 

94 probabilities = exp / total.clamp_min(torch.finfo(torch.float32).tiny) 

95 output = torch.einsum("tngk,tnkd->tngd", probabilities, selected.float()).flatten(1, 2) 

96 output = F.pad(output, (0, q_rope.shape[-1])) 

97 else: 

98 output = _parameter_sink( 

99 query[start:end], q_rope[start:end], selected, scores, sink_key, sink_value, 

100 start, end, x.shape[1], scale, dropout, 

101 ) 

102 outputs.append(output.to(x.dtype)) 

103 maxima.append(maximum.detach().squeeze(-1)) 

104 totals.append(total.detach().squeeze(-1)) 

105 return ( 

106 torch.cat(outputs).reshape(*x.shape[:3], -1), 

107 torch.cat(maxima).transpose(0, 1).contiguous(), 

108 torch.cat(totals).transpose(0, 1).contiguous(), 

109 ) 

110 

111 

112def _parameter_sink( 

113 query: torch.Tensor, rope: torch.Tensor, selected: torch.Tensor, scores: torch.Tensor, 

114 sink_key: torch.Tensor, sink_value: torch.Tensor, start: int, end: int, seq_len: int, 

115 scale: float, dropout: float, 

116) -> torch.Tensor: 

117 """Combine sparse attention with learnable parameter-sink contributions.""" 

118 batch_ids = torch.arange(start, end, device=query.device) // seq_len 

119 keys, values = sink_key[batch_ids].float(), sink_value[batch_ids].float() 

120 queries = torch.cat((query, rope), dim=-1).float() 

121 sink_scores = torch.einsum("thd,tshd->ths", queries, keys) * scale 

122 probabilities = torch.cat((scores.flatten(1, 2), sink_scores), dim=-1).softmax(-1) 

123 sparse_prob, sink_prob = probabilities.split((scores.shape[-1], sink_scores.shape[-1]), dim=-1) 

124 sparse_out = torch.einsum("tngk,tnkd->tngd", sparse_prob.reshape_as(scores), 

125 selected.float()).flatten(1, 2) 

126 sparse_out = F.pad(sparse_out, (0, rope.shape[-1])) 

127 sink_out = torch.einsum("ths,tshd->thd", F.dropout(sink_prob, dropout), values) 

128 return sparse_out + sink_out 

129 

130 

131def _cann_absorbed( 

132 x: torch.Tensor, key: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor, 

133 topk_indices: torch.Tensor, scale: float, query_ends: torch.Tensor, key_ends: torch.Tensor, 

134 *, sink_key: torch.Tensor | None = None, sink_value: torch.Tensor | None = None, dropout: float = 0.0, 

135) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

136 del sink_key, sink_value, dropout 

137 return fused_packed_attention(x, key, query_rope, key_rope, topk_indices, scale, query_ends, key_ends) 

138 

139 

140def _load_cann_absorbed() -> PackedDeepseekSparseAttentionFn: 

141 require_symbol(require_package("torch_npu"), "npu_sparse_flash_attention") 

142 require_symbol(require_package("cann_ops_transformer.ops"), "sparse_flash_attention_grad") 

143 return _cann_absorbed 

144 

145 

146def _load_omni_sink() -> PackedDeepseekSparseAttentionFn: 

147 """Load the optional Omni parameter-sink attention adapter.""" 

148 require_package("omni_training_custom_ops") 

149 extension = require_package("torch_npu") 

150 require_symbol(extension, "npu_fusion_attention") 

151 require_symbol(extension, "npu_fusion_attention_grad") 

152 require_symbol(torch.ops.custom, "npu_sparse_flash_attention_enhance") 

153 require_symbol(torch.ops.custom, "npu_sparse_flash_attention_grad_enhance") 

154 # Parameter-sink rescaling imports the optional Omni extension. 

155 from hyper_parallel.components.functional.dsa_sparse_attention_rescale import ( # pylint: disable=C0415 

156 dsa_sparse_attention_rescale, 

157 ) 

158 

159 def run( 

160 x: torch.Tensor, key: torch.Tensor, query_rope: torch.Tensor, key_rope: torch.Tensor, 

161 topk_indices: torch.Tensor, scale: float, query_ends: torch.Tensor, key_ends: torch.Tensor, 

162 *, sink_key: torch.Tensor | None = None, sink_value: torch.Tensor | None = None, dropout: float = 0.0, 

163 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

164 """Run parameter-sink sparse attention with the shared packed contract.""" 

165 return dsa_sparse_attention_rescale( 

166 x, key, query_rope, key_rope, sink_key, sink_value, topk_indices, 

167 *x.shape[:3], scale, 1.0 - dropout, query_ends, key_ends, 

168 ) 

169 

170 return run 

171 

172 

173def build_sliding_window_indices( 

174 batch_size: int, 

175 sequence_length: int, 

176 window_size: int, 

177 device: torch.device, 

178 *, 

179 query_offset: int = 0, 

180 key_length: int | None = None, 

181) -> torch.Tensor: 

182 """Build fixed-width causal sliding-window indices.""" 

183 if key_length is None: 

184 key_length = sequence_length 

185 width = min(key_length, window_size) 

186 query = torch.arange( 

187 query_offset, 

188 query_offset + sequence_length, 

189 device=device, 

190 ).unsqueeze(-1) 

191 offsets = torch.arange(width - 1, -1, -1, device=device) 

192 indices = query - offsets 

193 indices = indices.masked_fill(indices < 0, -1) 

194 return indices.unsqueeze(0).expand(batch_size, -1, -1) 

195 

196 

197def reference_sparse_attention( 

198 query: torch.Tensor, 

199 key_value: torch.Tensor, 

200 sparse_indices: torch.Tensor, 

201 sinks: torch.Tensor, 

202 scale: float, 

203) -> torch.Tensor: 

204 """Compute sink attention with eager Torch operations on any device. 

205 

206 Args: 

207 query: Main queries [batch, heads, local queries, head dimension]. 

208 key_value: Shared K=V bank [batch, 1, keys, head dimension]. 

209 sparse_indices: Visible bank IDs [batch, local queries, selections]; 

210 negative entries are padding and repeated IDs count only once. 

211 sinks: Learnable scalar sink logits [heads], with zero-valued output. 

212 scale: Main attention logit scale. 

213 

214 Returns: 

215 Attention values [batch, local queries, heads, head dimension]. 

216 Softmax uses FP32; matrix multiplications retain the input precision. 

217 

218 Note: 

219 This reference materializes a dense query/key mask and scores. It is 

220 intended for explicit unfused comparisons, not long-sequence efficiency. 

221 """ 

222 batch_size, num_heads, sequence_length, _ = query.shape 

223 key_length = key_value.shape[2] 

224 valid = sparse_indices >= 0 

225 safe_indices = sparse_indices.clamp_min(0).long() 

226 allowed_counts = torch.zeros( 

227 batch_size, 

228 sequence_length, 

229 key_length, 

230 dtype=torch.int32, 

231 device=query.device, 

232 ) 

233 allowed_counts.scatter_add_(2, safe_indices, valid.to(torch.int32)) 

234 allowed = allowed_counts > 0 

235 logits = torch.matmul(query, key_value.transpose(-1, -2)) * scale 

236 logits = logits.masked_fill(~allowed.unsqueeze(1), float("-inf")) 

237 sink_logits = sinks.view(1, num_heads, 1, 1).expand(batch_size, -1, sequence_length, -1) 

238 probabilities = torch.cat((logits, sink_logits), dim=-1).softmax(dim=-1, dtype=torch.float32) 

239 return torch.matmul(probabilities[..., :-1].to(key_value.dtype), key_value).transpose(1, 2) 

240 

241 

242def native_deepseek_sparse_attention( 

243 x: torch.Tensor, raw_key: torch.Tensor, compressed_key: torch.Tensor | None, 

244 topk_indices: torch.Tensor | None, sinks: torch.Tensor, *, scale: float, window: int, 

245 layout: DsaQueryLayout, global_sequence_length: int, raw_key_offset: int = 0, 

246 main_key_offset: int = 0, global_key_length: int | None = None, 

247) -> torch.Tensor: 

248 """Assemble the reference sliding-window and compressed key indices.""" 

249 raw_indices = build_sliding_window_indices( 

250 raw_key.shape[0], x.shape[2], window, raw_key.device, 

251 query_offset=layout.query_offset, key_length=global_sequence_length, 

252 ) 

253 starts = layout.segment_starts 

254 if starts is None and layout.segments is not None: 

255 starts = torch.zeros(x.shape[2], dtype=torch.long, device=x.device) 

256 for (begin, end, *_), (_, origin) in zip(layout.segments, layout.raw_document_starts()): 

257 starts[begin:end] = origin 

258 starts = starts.unsqueeze(0) 

259 if starts is not None: 

260 raw_indices = raw_indices.masked_fill(raw_indices < starts.unsqueeze(-1), -1) 

261 raw_indices = torch.where(raw_indices >= 0, raw_indices - raw_key_offset, -1) 

262 if compressed_key is None: 

263 return reference_sparse_attention(x, raw_key, raw_indices, sinks, scale) 

264 indices = topk_indices 

265 if global_key_length is not None: 

266 indices = indices.masked_fill(indices >= global_key_length, -1) 

267 indices = torch.where(indices >= 0, indices.long() - main_key_offset + raw_key.shape[2], -1) 

268 return reference_sparse_attention( 

269 x, torch.cat((raw_key, compressed_key.unsqueeze(1)), dim=2), 

270 torch.cat((raw_indices, indices), dim=-1), sinks, scale, 

271 ) 

272 

273 

274def attention_native_only( 

275 x: torch.Tensor, layout: DsaQueryLayout, window: int, topk_indices: torch.Tensor | None, 

276 global_sequence_length: int, global_key_length: int | None, 

277) -> str | None: 

278 """Explain incompatible layouts before attempting to load Sparse Flash MLA.""" 

279 ratio = layout.compress_ratio 

280 topk = 0 if topk_indices is None else topk_indices.shape[-1] 

281 expected = global_sequence_length // max(1, ratio) if global_key_length is None else global_key_length 

282 if (layout.segments is None or (topk_indices is not None and topk != min(512, expected)) 

283 or not supports_fused_attention_inputs(x, ratio, window, topk)): 

284 return "Sparse Flash MLA requires supported BF16 NPU inputs, document segments and ordinary TopK" 

285 return None 

286 

287 

288def _cann_attention( 

289 x: torch.Tensor, raw_key: torch.Tensor, compressed_key: torch.Tensor | None, 

290 topk_indices: torch.Tensor | None, sinks: torch.Tensor, *, scale: float, window: int, 

291 layout: DsaQueryLayout, global_sequence_length: int, raw_key_offset: int = 0, 

292 main_key_offset: int = 0, global_key_length: int | None = None, 

293) -> torch.Tensor: 

294 """Run compressed-bank sparse MLA through the CANN adapter.""" 

295 del global_sequence_length, global_key_length 

296 output = sparse_flash_mla( 

297 x, raw_key, compressed_key, topk_indices, sinks, scale, layout.compress_ratio, window, 

298 layout.query_offset, layout.segments, raw_key_offset, main_key_offset, layout.raw_document_starts(), 

299 ) 

300 if compressed_key is not None and all(end == start for _, _, start, end, _ in layout.segments): 

301 # Keep the shared bank's collective backward active on empty-prefix ranks. 

302 output = output + compressed_key[:, :0].sum().to(output.dtype) 

303 return output 

304 

305 

306def register_deepseek_sparse_attention(registry: OpRegistry) -> None: 

307 """Register the compressed-banks attention contract and its implementations.""" 

308 registry.register_family("deepseek_sparse_attention", specs=(DSA_COMPRESSED_BANKS, DSA_ABSORBED, DSA_ABSORBED_SINK)) 

309 registry.register_impl( 

310 DSA_COMPRESSED_BANKS, name="native", devices=("cpu", "cuda", "npu"), 

311 load=lambda: native_deepseek_sparse_attention, 

312 ) 

313 registry.register_impl( 

314 DSA_COMPRESSED_BANKS, name="cann", devices=("npu",), 

315 load=partial(load_cann, _cann_attention, "sparse_flash_mla", "sparse_flash_mla_grad", 

316 "sparse_flash_mla_metadata"), 

317 ) 

318 for spec in (DSA_ABSORBED, DSA_ABSORBED_SINK): 

319 registry.register_impl(spec, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native_absorbed) 

320 registry.register_impl(DSA_ABSORBED, name="cann", devices=("npu",), load=_load_cann_absorbed) 

321 registry.register_impl(DSA_ABSORBED_SINK, name="omni", devices=("npu",), load=_load_omni_sink)