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

62 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"""DSA sparse-attention function.""" 

16 

17from typing import Any, Tuple 

18 

19import torch 

20import torch.nn.functional as F 

21from einops import rearrange 

22 

23from hyper_parallel.tools.logging import get_logger 

24 

25logger = get_logger() 

26 

27 

28def _load_sparse_attention_grad(): 

29 """Defer the optional NPU dependency until sparse-attention backward.""" 

30 from cann_ops_transformer.ops import sparse_flash_attention_grad # pylint: disable=import-outside-toplevel 

31 

32 return sparse_flash_attention_grad 

33 

34 

35def _sparse_attention_forward( 

36 query: torch.Tensor, 

37 key: torch.Tensor, 

38 indices: torch.Tensor, 

39 scale: float, 

40 query_rope: torch.Tensor | None, 

41 key_rope: torch.Tensor | None, 

42 query_lengths: torch.Tensor | None, 

43 key_lengths: torch.Tensor | None, 

44 layout: str, 

45 attention_op: Any, 

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

47 """Call torch_npu SparseFlashAttention with the V3.2 DSA contract.""" 

48 kwargs = { 

49 "query_rope": None if query_rope is None else query_rope.contiguous(), 

50 "key_rope": None if key_rope is None else key_rope.contiguous(), 

51 "sparse_block_size": 1, 

52 "layout_query": layout, 

53 "layout_kv": layout, 

54 "sparse_mode": 3, 

55 "attention_mode": 2, 

56 "return_softmax_lse": True, 

57 } 

58 if layout == "TND": 

59 kwargs.update({"actual_seq_lengths_query": query_lengths, "actual_seq_lengths_kv": key_lengths}) 

60 key = key.contiguous() 

61 return attention_op(query.contiguous(), key, key, indices.contiguous(), scale, **kwargs) 

62 

63 

64def _sparse_attention_backward( 

65 query: torch.Tensor, 

66 key: torch.Tensor, 

67 indices: torch.Tensor, 

68 grad_output: torch.Tensor, 

69 output: torch.Tensor, 

70 maximum: torch.Tensor, 

71 total: torch.Tensor, 

72 scale: float, 

73 query_rope: torch.Tensor | None, 

74 key_rope: torch.Tensor | None, 

75 query_lengths: torch.Tensor | None, 

76 key_lengths: torch.Tensor | None, 

77 layout: str, 

78 grad_op: Any, 

79) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None, torch.Tensor | None]: 

80 """Pass shared K/V explicitly and merge their gradients for the shared input.""" 

81 key = key.contiguous() 

82 result = grad_op( 

83 query.contiguous(), key, key, 

84 indices.contiguous(), grad_output.contiguous(), 

85 output.contiguous(), maximum.contiguous(), total.contiguous(), None, scale, 1, 

86 query_rope=None if query_rope is None else query_rope.contiguous(), 

87 key_rope=None if key_rope is None else key_rope.contiguous(), 

88 actual_seq_qlen=query_lengths, 

89 actual_seq_kvlen=key_lengths, 

90 layout=layout, 

91 sparse_mode=3, 

92 attention_mode=2, 

93 ) 

94 grad_query, grad_key, grad_value, grad_query_rope, grad_key_rope, _ = result 

95 shared_key_gradient = grad_key + grad_value 

96 return ( 

97 grad_query, 

98 shared_key_gradient, 

99 None if query_rope is None else grad_query_rope, 

100 None if key_rope is None else grad_key_rope, 

101 ) 

102 

103 

104class _SparseAttention(torch.autograd.Function): 

105 """Pair torch_npu sparse-attention forward with the available CANN backward API.""" 

106 

107 @staticmethod 

108 def forward( 

109 ctx: Any, 

110 query: torch.Tensor, 

111 key: torch.Tensor, 

112 indices: torch.Tensor, 

113 query_rope: torch.Tensor | None, 

114 key_rope: torch.Tensor | None, 

115 qlen: torch.Tensor | None, 

116 klen: torch.Tensor | None, 

117 scale: float, 

118 layout: str, 

119 attention_op: Any, 

120 grad_op: Any, 

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

122 """Run sparse attention and save inputs needed by its backward pass.""" 

123 outputs = _sparse_attention_forward( 

124 query, key, indices, scale, query_rope, key_rope, qlen, klen, layout, attention_op, 

125 ) 

126 optional_inputs = (query_rope, key_rope, qlen, klen) 

127 ctx.optional_input_mask = tuple(tensor is not None for tensor in optional_inputs) 

128 saved_inputs = [query, key, indices] 

129 saved_inputs.extend(tensor for tensor in optional_inputs if tensor is not None) 

130 ctx.save_for_backward(*saved_inputs, *outputs) 

131 ctx.scale, ctx.layout, ctx.grad_op = scale, layout, grad_op 

132 ctx.mark_non_differentiable(*outputs[1:]) 

133 return outputs 

134 

135 @staticmethod 

136 def backward( 

137 ctx: Any, 

138 grad_output: torch.Tensor, 

139 gradmax: torch.Tensor | None, 

140 gradsum: torch.Tensor | None, 

141 ) -> tuple[torch.Tensor | None, ...]: 

142 """Compute gradients for differentiable sparse-attention inputs.""" 

143 del gradmax, gradsum 

144 saved = iter(ctx.saved_tensors) 

145 query, key, indices = (next(saved) for _ in range(3)) 

146 optional_inputs = tuple(next(saved) if present else None for present in ctx.optional_input_mask) 

147 query_rope, key_rope, qlen, klen = optional_inputs 

148 output, maximum, total = (next(saved) for _ in range(3)) 

149 gradients = _sparse_attention_backward( 

150 query, key, indices, grad_output, output, maximum, total, ctx.scale, 

151 query_rope, key_rope, qlen, klen, ctx.layout, ctx.grad_op(), 

152 ) 

153 return gradients[0], gradients[1], None, *gradients[2:], None, None, None, None, None, None 

154 

155 

156def _cann_sparse_attention( 

157 query: torch.Tensor, 

158 key: torch.Tensor, 

159 sparse_indices: torch.Tensor, 

160 scale: float, 

161 *, 

162 query_rope: torch.Tensor | None, 

163 key_rope: torch.Tensor | None, 

164 query_lengths: torch.Tensor | None, 

165 key_lengths: torch.Tensor | None, 

166 layout: str, 

167 attention_op: Any, 

168 grad_op: Any, 

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

170 """Run CANN sparse attention with the matching backward API and return statistics.""" 

171 return _SparseAttention.apply( 

172 query, key, sparse_indices, query_rope, key_rope, 

173 query_lengths, key_lengths, scale, layout, attention_op, grad_op, 

174 ) 

175 

176 

177def dsa_sparse_attention( 

178 query_nope: torch.Tensor, 

179 compressed_kv: torch.Tensor, 

180 query_rope: torch.Tensor, 

181 key_rope: torch.Tensor, 

182 topk_indices: torch.Tensor, 

183 scale: float, 

184 actual_seq_qlen: torch.Tensor, 

185 actual_seq_kvlen: torch.Tensor, 

186 *, 

187 backend: str = "cann", 

188) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

189 """Compute NPU DSA sparse flash attention without parameter-sink rescaling. 

190 

191 Args: 

192 query_nope: Absorbed MLA query in BSND layout. 

193 compressed_kv: Compressed MLA key/value in BSND layout. 

194 query_rope: Query rotary states in BSND layout. 

195 key_rope: Key rotary states in BSND layout. 

196 topk_indices: Int32 ``[T, N_kv, K]`` output from :func:`dsa_indexer`. 

197 scale: Attention score scaling factor. 

198 actual_seq_qlen: Cumulative query lengths as an int32 NPU tensor. 

199 actual_seq_kvlen: Cumulative key lengths as an int32 NPU tensor. 

200 backend: ``"cann"`` (default) or the legacy ``"omni"`` backend. 

201 

202 Returns: 

203 Attention output in BSND layout, followed by the softmax maximum and 

204 sum required by :func:`dsa_kl_loss`. The output head dimension contains 

205 the compressed-KV dimension followed by zero padding for the RoPE 

206 dimension required by the sparse-attention backward operator. 

207 """ 

208 if backend not in ("cann", "omni"): 

209 raise ValueError(f"backend must be 'cann' or 'omni', got {backend!r}") 

210 query_tnd = rearrange(query_nope, "b s n d -> (b s) n d") 

211 key_tnd = rearrange(compressed_kv, "b s n d -> (b s) n d") 

212 query_rope_tnd = rearrange(query_rope, "b s n d -> (b s) n d") 

213 key_rope_tnd = rearrange(key_rope, "b s n d -> (b s) n d") 

214 # Load only the selected optional backend so either can be used independently. 

215 # pylint: disable=import-outside-toplevel 

216 if backend == "cann": 

217 import torch_npu 

218 

219 output, softmax_max, softmax_sum = _cann_sparse_attention( 

220 query_tnd, 

221 key_tnd, 

222 topk_indices, 

223 scale, 

224 query_rope=query_rope_tnd, 

225 key_rope=key_rope_tnd, 

226 query_lengths=actual_seq_qlen, 

227 key_lengths=actual_seq_kvlen, 

228 layout="TND", 

229 attention_op=torch_npu.npu_sparse_flash_attention, 

230 grad_op=_load_sparse_attention_grad, 

231 ) 

232 else: 

233 logger.warning( 

234 "dsa_sparse_attention backend='omni' is deprecated and will be removed in a future release; " 

235 "use backend='cann'." 

236 ) 

237 import omni_training_custom_ops # noqa: F401 # pylint: disable=unused-import 

238 

239 output, softmax_max, softmax_sum = torch.ops.custom.npu_sparse_flash_attention_enhance( 

240 query_tnd, 

241 key_tnd, 

242 key_tnd, 

243 topk_indices, 

244 scale, 

245 block_table=None, 

246 actual_seq_lengths_query=actual_seq_qlen, 

247 actual_seq_lengths_kv=actual_seq_kvlen, 

248 query_rope=query_rope_tnd, 

249 key_rope=key_rope_tnd, 

250 sparse_block_size=1, 

251 layout_query="TND", 

252 layout_kv="TND", 

253 sparse_mode=3, 

254 attention_mode=2, 

255 return_softmax_lse=True, 

256 ) 

257 # pylint: enable=import-outside-toplevel 

258 if query_rope.size(-1) > 0: 

259 output = F.pad(output, [0, query_rope.size(-1)]) 

260 output = rearrange(output, "(b s) n d -> b s n d", b=query_nope.shape[0]) 

261 return output, softmax_max, softmax_sum