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

195 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"""Dense, grouped-query and vision attention with canonical BNSD inputs.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable 

20from typing import Protocol 

21 

22import torch 

23from torch.nn import functional as F 

24 

25from hyper_parallel.components.functional.npu_fusion_attention import npu_fusion_attention_forward 

26 

27from ..registry import OpRegistry 

28from ..spec import OpSpec 

29from .._dependency import require_package, require_symbol 

30from .._dsa_layout import packed_segments 

31 

32 

33class VisionAttentionFn(Protocol): 

34 """Compute dropout-free bidirectional attention and return BSND output.""" 

35 

36 def __call__(self, x: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor: 

37 """Return attention over all supplied valid keys.""" 

38 

39 

40AttentionLengths = tuple[list[int], list[int]] 

41 

42 

43class DenseAttentionFn(Protocol): 

44 """Attend in BNSD layout and return BSND without materialized weights.""" 

45 

46 def __call__( 

47 self, x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None, 

48 *, causal: bool, scale: float, dropout: float, window: int | None, 

49 lengths: AttentionLengths | None, query_offset: int | None, 

50 ) -> torch.Tensor: 

51 """Apply padding or pairwise masks, packed document ends and the causal window.""" 

52 

53 

54VISION_ATTENTION = OpSpec[VisionAttentionFn](config_key="attention", variant="vision") 

55GROUPED_QUERY_ATTENTION = OpSpec[DenseAttentionFn](config_key="attention", variant="gqa") 

56MULTI_LATENT_ATTENTION = OpSpec[DenseAttentionFn](config_key="attention", variant="mla") 

57 

58 

59class MultiLatentAttentionStatsFn(Protocol): 

60 """Run packed causal MLA and optionally return detached teacher statistics.""" 

61 

62 def __call__( 

63 self, x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, 

64 query_ends: torch.Tensor, key_ends: torch.Tensor, *, scale: float, need_stats: bool, 

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

66 """Return BSND output and optional H,T,1 softmax maximum and exponential sum.""" 

67 

68 

69MULTI_LATENT_ATTENTION_WITH_STATS = OpSpec[MultiLatentAttentionStatsFn]( 

70 config_key="attention", variant="mla_with_stats", 

71) 

72 

73 

74def _native(x: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor: 

75 accumulator = torch.float32 if x.dtype in (torch.float16, torch.bfloat16) else x.dtype 

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

77 scores = (x.to(accumulator) @ key.to(accumulator).transpose(-1, -2)) * (x.shape[-1] ** -0.5) 

78 return (scores.softmax(dim=-1) @ value.to(accumulator)).to(x.dtype).transpose(1, 2) 

79 

80 

81def _sdpa(x: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor: 

82 return F.scaled_dot_product_attention(x, key, value, is_causal=False).transpose(1, 2) # pylint: disable=not-callable 

83 

84 

85def _npu(x: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor: 

86 output, _ = npu_fusion_attention_forward( 

87 None, x, key, value, attention_mask=None, 

88 dropout=0.0, scaling=x.shape[-1] ** -0.5, is_causal=False, sparse_mode=0, 

89 pre_tokens=2147483647, next_tokens=2147483647, 

90 ) 

91 return output 

92 

93 

94def _load_npu() -> VisionAttentionFn: 

95 require_symbol(require_package("torch_npu"), "npu_fusion_attention") 

96 return _npu 

97 

98 

99def _causal_mask( 

100 query: torch.Tensor, key: torch.Tensor, window: int | None, query_offset: int | None, 

101) -> torch.Tensor: 

102 offset = max(0, key.shape[2] - query.shape[2]) if query_offset is None else query_offset 

103 q_pos = (torch.arange(query.shape[2], device=query.device) + offset).unsqueeze(1) 

104 k_pos = torch.arange(key.shape[2], device=query.device) 

105 allowed = k_pos <= q_pos 

106 return allowed if window is None else allowed & (k_pos > q_pos - window) 

107 

108 

109def _torch_dense( 

110 query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None, 

111 scale: float, dropout: float, 

112) -> torch.Tensor: 

113 """Compute dense attention with FP32 accumulation and explicit masking.""" 

114 groups = query.shape[1] // key.shape[1] 

115 if groups > 1: 

116 key, value = (tensor.repeat_interleave(groups, dim=1) for tensor in (key, value)) 

117 dtype = torch.float32 if query.dtype in (torch.float16, torch.bfloat16) else query.dtype 

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

119 scores = (query.to(dtype) @ key.to(dtype).transpose(-1, -2)) * scale 

120 if mask is not None: 

121 valid = mask.any(dim=-1, keepdim=True) 

122 scores = scores.masked_fill(~mask & valid, float("-inf")) 

123 probabilities = torch.softmax(scores, dim=-1) 

124 if mask is not None: 

125 probabilities = probabilities.masked_fill(~mask, 0) 

126 return (F.dropout(probabilities, dropout) @ value.to(dtype)).to(query.dtype) 

127 

128 

129def _sdpa_dense( 

130 query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None, 

131 scale: float, dropout: float, 

132) -> torch.Tensor: 

133 return F.scaled_dot_product_attention( # pylint: disable=not-callable 

134 query, key, value, attn_mask=mask, dropout_p=dropout, scale=scale, 

135 enable_gqa=query.shape[1] != key.shape[1], 

136 ) 

137 

138 

139def _make_dense_reference(kernel: Callable[..., torch.Tensor]) -> DenseAttentionFn: 

140 """Bind a dense attention kernel to the shared reference contract.""" 

141 def dense( 

142 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None, 

143 *, causal: bool, scale: float, dropout: float, window: int | None, 

144 lengths: AttentionLengths | None, query_offset: int | None, 

145 ) -> torch.Tensor: 

146 """Resolve packed boundaries and masks before running the dense kernel.""" 

147 if lengths is not None: 

148 return _packed_reference(kernel, x, key, value, mask, lengths, causal, scale, dropout, window) 

149 padding = None 

150 if mask is not None: 

151 mask = mask.to(device=x.device) 

152 if mask.ndim == 2: 

153 padding = mask.to(torch.bool) 

154 mask = padding[:, None, None, :] 

155 elif mask.dtype != torch.bool: 

156 mask = mask == 0 

157 if causal: 

158 allowed = _causal_mask(x, key, window, query_offset) 

159 mask = allowed if mask is None else mask & allowed 

160 output = kernel(x, key, value, mask, scale, dropout).transpose(1, 2) 

161 if padding is not None and causal and x.shape[2] == key.shape[2]: 

162 output = output.masked_fill(~padding[:, :, None, None], 0) 

163 return output 

164 

165 return dense 

166 

167 

168def _packed_reference( 

169 kernel: Callable[..., torch.Tensor], x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, 

170 mask: torch.Tensor | None, lengths: AttentionLengths, causal: bool, scale: float, 

171 dropout: float, window: int | None, 

172) -> torch.Tensor: 

173 """Evaluate independent packed documents with their local masks.""" 

174 q_ends, k_ends = lengths 

175 padding = None 

176 if mask is not None: 

177 mask = mask.to(device=x.device) 

178 if mask.ndim == 2: 

179 padding = mask.to(torch.bool).expand(key.shape[0], -1).flatten() 

180 if padding.numel() != key.shape[0] * key.shape[2]: 

181 raise ValueError("Packed attention padding must cover the physical key tokens") 

182 mask = None 

183 elif mask.dtype != torch.bool: 

184 mask = mask == 0 

185 q_flat, k_flat, v_flat = (tensor.transpose(1, 2).flatten(0, 1).transpose(0, 1) 

186 for tensor in (x, key, value)) 

187 segments = [] 

188 for qs, qe, ks, ke in zip([0, *q_ends[:-1]], q_ends, [0, *k_ends[:-1]], k_ends): 

189 q_chunk, k_chunk, v_chunk = (q_flat[:, qs:qe], k_flat[:, ks:ke], v_flat[:, ks:ke]) 

190 local_mask = None if not causal else _causal_mask(q_chunk[None], k_chunk[None], window, None) 

191 if padding is not None: 

192 valid_keys = padding[ks:ke][None, :] 

193 local_mask = valid_keys if local_mask is None else local_mask & valid_keys 

194 if mask is not None: 

195 packed_mask = _packed_pair_mask(mask, qs, qe, ks, ke, x, key) 

196 local_mask = packed_mask if local_mask is None else packed_mask & local_mask 

197 chunk = kernel(q_chunk[None], k_chunk[None], v_chunk[None], local_mask, scale, dropout) 

198 if padding is not None and causal and q_ends == k_ends: 

199 chunk = chunk.masked_fill(~padding[qs:qe][None, None, :, None], 0) 

200 segments.append(chunk.squeeze(0).transpose(0, 1)) 

201 return torch.cat(segments).reshape(x.shape[0], x.shape[2], x.shape[1], value.shape[-1]) 

202 

203 

204def _packed_pair_mask( 

205 mask: torch.Tensor, qs: int, qe: int, ks: int, ke: int, query: torch.Tensor, key: torch.Tensor, 

206) -> torch.Tensor: 

207 """Slice a pairwise mask using packed or batch-local token coordinates.""" 

208 q_len, k_len = query.shape[2], key.shape[2] 

209 if mask.shape[-2:] == (query.shape[0] * q_len, key.shape[0] * k_len): 

210 return mask[..., qs:qe, ks:ke] 

211 q_batch, q_start = divmod(qs, q_len) 

212 k_batch, k_start = divmod(ks, k_len) 

213 q_stop, k_stop = q_start + qe - qs, k_start + ke - ks 

214 if q_batch != k_batch or q_stop > q_len or k_stop > k_len: 

215 raise ValueError("A packed pairwise mask must use flattened token indices when a segment spans batches") 

216 if mask.ndim == 4 and mask.shape[0] > 1: 

217 mask = mask[q_batch:q_batch + 1] 

218 return mask[..., q_start:q_stop, k_start:k_stop] 

219 

220 

221def _npu_dense( 

222 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, mask: torch.Tensor | None, 

223 *, causal: bool, scale: float, dropout: float, window: int | None, 

224 lengths: AttentionLengths | None, query_offset: int | None, 

225) -> torch.Tensor: 

226 """Translate dense attention arguments for the NPU fusion kernel.""" 

227 options = {} if lengths is None else {"actual_q_len": lengths[0], "actual_kv_len": lengths[1]} 

228 if query_offset is not None and causal and lengths is None: 

229 if mask is not None and mask.ndim == 2: 

230 mask = mask.to(torch.bool)[:, None, None, :] 

231 if mask is not None and mask.dtype != torch.bool: 

232 mask = mask == 0 

233 causal_mask = _causal_mask(x, key, window, query_offset) 

234 mask = causal_mask if mask is None else causal_mask & mask 

235 causal = False 

236 output, _ = npu_fusion_attention_forward( 

237 None, x, key, value, mask, dropout=dropout, scaling=scale, 

238 is_causal=causal, sliding_window=window, **options, 

239 ) 

240 return output 

241 

242 

243def _load_npu_dense() -> DenseAttentionFn: 

244 require_symbol(require_package("torch_npu"), "npu_fusion_attention") 

245 return _npu_dense 

246 

247 

248def _npu_mla_with_stats( 

249 query: torch.Tensor, 

250 key: torch.Tensor, 

251 value: torch.Tensor, 

252 query_ends: torch.Tensor, 

253 key_ends: torch.Tensor, 

254 *, 

255 scale: float, 

256 need_stats: bool, 

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

258 """Run one TND FA and return dense-indexer statistics.""" 

259 query_ends, key_ends = query_ends.tolist(), key_ends.tolist() 

260 q_flat, k_flat, v_flat = (tensor.flatten(0, 1) for tensor in (query, key, value)) 

261 num_heads = q_flat.shape[1] 

262 causal_mask = torch.ones((2048, 2048), dtype=torch.bool, device=query.device).triu(diagonal=1) 

263 # The native training kernel is optional outside the Ascend backend. 

264 import torch_npu # pylint: disable=import-outside-toplevel 

265 

266 result = torch_npu.npu_fusion_attention( 

267 q_flat.contiguous(), k_flat.contiguous(), v_flat.contiguous(), num_heads, "TND", 

268 pse=None, padding_mask=None, atten_mask=causal_mask, scale=scale, 

269 pre_tockens=1048576, next_tockens=0, keep_prob=1.0, inner_precise=0, 

270 actual_seq_qlen=query_ends, actual_seq_kvlen=key_ends, sparse_mode=3, 

271 ) 

272 output = result[0].reshape(*query.shape[:3], value.shape[-1]) 

273 if not need_stats: 

274 return output, None, None 

275 

276 # TND FA stores each packed segment as [head, token, 8], while exposing a 

277 # physical [token, head, 8] shape. Dense KL consumes [head, token, 1]. 

278 statistics = [] 

279 starts = [0, *query_ends[:-1]] 

280 for statistic in result[1:3]: 

281 rows = statistic.reshape(-1, statistic.shape[-1]) 

282 segments = [ 

283 rows[start * num_heads : end * num_heads].reshape( 

284 num_heads, end - start, statistic.shape[-1] 

285 )[..., :1] 

286 for start, end in zip(starts, query_ends) 

287 ] 

288 statistics.append(torch.cat(segments, dim=1).detach()) 

289 return output, statistics[0], statistics[1] 

290 

291 

292def _make_mla_stats_reference(*, sdpa: bool = False) -> MultiLatentAttentionStatsFn: 

293 """Build packed MLA attention with optional detached softmax statistics.""" 

294 def run( 

295 x: torch.Tensor, key: torch.Tensor, value: torch.Tensor, 

296 query_ends: torch.Tensor, key_ends: torch.Tensor, *, scale: float, need_stats: bool, 

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

298 """Return packed MLA output and optional detached teacher statistics.""" 

299 q_flat, k_flat, v_flat = (tensor.flatten(0, 1).transpose(0, 1) for tensor in (x, key, value)) 

300 output, maxima, totals = [], [], [] 

301 dtype = torch.float32 if x.dtype in (torch.bfloat16, torch.float16) else x.dtype 

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

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

304 q, k, v = q_flat[:, qs:qe], k_flat[:, ks:ke], v_flat[:, ks:ke] 

305 for start in range(0, qe - qs, 128): 

306 end = min(start + 128, qe - qs) 

307 local_q = q[:, start:end] 

308 mask = _causal_mask(local_q[None], k[None], None, start + ke - ks - (qe - qs)) 

309 if sdpa: 

310 output.append(_sdpa_dense(local_q[None], k[None], v[None], mask, scale, 0.0)[0]) 

311 if need_stats or not sdpa: 

312 scores = (local_q.to(dtype) @ k.to(dtype).transpose(-1, -2)) * scale 

313 scores = scores.masked_fill(~mask, -torch.inf) 

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

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

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

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

318 if not sdpa: 

319 probabilities = exp / total.clamp_min(torch.finfo(dtype).tiny) 

320 output.append((probabilities @ v.to(dtype)).to(x.dtype)) 

321 if need_stats: 

322 maxima.append(maximum.detach()) 

323 totals.append(total.detach()) 

324 attention = torch.cat(output, dim=1).transpose(0, 1).reshape(*x.shape[:3], value.shape[-1]) 

325 if not need_stats: 

326 return attention, None, None 

327 return attention, torch.cat(maxima, dim=1), torch.cat(totals, dim=1) 

328 

329 return run 

330 

331 

332def _load_npu_mla_stats() -> MultiLatentAttentionStatsFn: 

333 require_symbol(require_package("torch_npu"), "npu_fusion_attention") 

334 return _npu_mla_with_stats 

335 

336 

337def register_attention(registry: OpRegistry) -> None: 

338 """Register reference, SDPA and Ascend vision and dense attention.""" 

339 registry.register_family("attention", specs=( 

340 VISION_ATTENTION, GROUPED_QUERY_ATTENTION, MULTI_LATENT_ATTENTION, MULTI_LATENT_ATTENTION_WITH_STATS, 

341 )) 

342 registry.register_impl(VISION_ATTENTION, name="native", devices=("cpu", "cuda", "npu"), load=lambda: _native) 

343 registry.register_impl(VISION_ATTENTION, name="sdpa", devices=("cpu", "cuda"), load=lambda: _sdpa) 

344 registry.register_impl(VISION_ATTENTION, name="torch_npu", devices=("npu",), load=_load_npu) 

345 for spec in (GROUPED_QUERY_ATTENTION, MULTI_LATENT_ATTENTION): 

346 registry.register_impl(spec, name="native", devices=("cpu", "cuda", "npu"), 

347 load=lambda: _make_dense_reference(_torch_dense)) 

348 registry.register_impl( 

349 spec, name="sdpa", devices=("cpu", "cuda"), load=lambda: _make_dense_reference(_sdpa_dense), 

350 ) 

351 registry.register_impl(spec, name="torch_npu", devices=("npu",), load=_load_npu_dense) 

352 registry.register_impl( 

353 MULTI_LATENT_ATTENTION_WITH_STATS, name="native", devices=("cpu", "cuda", "npu"), 

354 load=_make_mla_stats_reference, 

355 ) 

356 registry.register_impl(MULTI_LATENT_ATTENTION_WITH_STATS, name="sdpa", devices=("cpu", "cuda"), 

357 load=lambda: _make_mla_stats_reference(sdpa=True)) 

358 registry.register_impl( 

359 MULTI_LATENT_ATTENTION_WITH_STATS, name="torch_npu", devices=("npu",), load=_load_npu_mla_stats, 

360 )