Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / functional / sparse_flash_mla.py: 92%
202 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"""SparseFlashMla forward/backward adapter for CSA with scalar attention sinks."""
17from __future__ import annotations
19from dataclasses import dataclass
20from functools import lru_cache
21from itertools import accumulate
22from typing import Any, Callable
24import torch
27_A5_DEVICE_MARKERS = ("Ascend950", "Ascend910_95")
30def pack_ranges(tensor: torch.Tensor, ranges: tuple[tuple[int, int], ...]) -> torch.Tensor:
31 """Pack token ranges without copying an already contiguous partition.
33 Args:
34 tensor: Source tensor with tokens on the first dimension.
35 ranges: Nonempty, ordered half-open token intervals.
37 Returns:
38 Contiguous packed tokens; autograd restores gradients to the source.
39 """
40 if all(left[1] == right[0] for left, right in zip(ranges, ranges[1:])):
41 start, end = ranges[0][0], ranges[-1][1]
42 if start == 0 and end == tensor.shape[0]:
43 return tensor.contiguous()
44 return tensor[start:end].contiguous()
45 return torch.cat([tensor[start:end] for start, end in ranges], dim=0).contiguous()
48@dataclass(frozen=True)
49class CSATNDPlan:
50 """Document-local lengths and canonical K offsets; no training activations."""
52 segments: tuple[tuple[int, int, int, int, int], ...]
53 q_ranges: tuple[tuple[int, int], ...]
54 k_ranges: tuple[tuple[int, int], ...]
55 q_lengths: tuple[int, ...]
56 k_lengths: tuple[int, ...]
57 residuals: tuple[int, ...]
59 def query(self, tensor: torch.Tensor) -> torch.Tensor:
60 """Pack a [1,Q,...] tensor in the plan's document order."""
61 return pack_ranges(tensor.squeeze(0), self.q_ranges)
63 def key(self, tensor: torch.Tensor, key_offset: int = 0) -> torch.Tensor:
64 """Pack global document prefixes using the physical origin of a [1,K,...] bank."""
65 ranges = self.k_ranges if not key_offset else tuple((start-key_offset, end-key_offset)
66 for start, end in self.k_ranges)
67 return pack_ranges(tensor.squeeze(0), ranges)
69 def lengths(self, device: torch.device) -> tuple:
70 """Reuse device length tensors, including across inference and recomputation."""
71 return _device_lengths(self, device)
73 def indexer_options(self, device: torch.device, ratio: int) -> dict:
74 """Share the document partition and causal mask between Indexer and KL."""
75 cu_q, cu_k, residuals, _ = self.lengths(device)
76 return {"cu_seqlens_q": cu_q, "cu_seqlens_k": cu_k,
77 "cmp_residual_k": residuals if ratio > 1 else None,
78 "layout_q": "TND", "layout_k": "TND", "mask_mode": 3, "cmp_ratio": ratio}
80 def local_indices(self, indices: torch.Tensor, padded_width: int = 0) -> torch.Tensor:
81 """Translate bank IDs; pad only when the consumer explicitly requires a width."""
82 selected = self.query(indices)
83 offsets = self.lengths(indices.device)[3]
84 selected = torch.where(selected >= 0, selected - offsets, -1).int()
85 if selected.shape[-1] < padded_width:
86 selected = torch.nn.functional.pad(selected, (0, padded_width-selected.shape[-1]), value=-1)
87 return selected.unsqueeze(1).contiguous()
89 def covers_queries(self, length: int) -> bool:
90 """Return whether packed rows already follow the complete original Q order."""
91 return (self.q_ranges[0][0] == 0 and self.q_ranges[-1][1] == length
92 and all(left[1] == right[0] for left, right in zip(self.q_ranges, self.q_ranges[1:])))
94 def restore(self, part: torch.Tensor, output: torch.Tensor) -> None:
95 """Write packed query rows into their original positions, preserving autograd."""
96 cursor = 0
97 for start, end in self.q_ranges:
98 output[0, start:end] = part[cursor:cursor+end-start]
99 cursor += end-start
102@lru_cache(maxsize=128)
103def csa_tnd_plan(segments: tuple, ratio: int, has_keys: bool = True) -> CSATNDPlan | None:
104 """Separate true SWA-only/empty-prefix queries without inventing valid keys."""
105 active = tuple(item for item in segments
106 if item[1] > item[0] and (bool(ratio and item[3] > item[2]) == has_keys))
107 if not active:
108 return None
109 return CSATNDPlan(
110 active, tuple((s, e) for s, e, _, _, _ in active), tuple((s, e) for _, _, s, e, _ in active),
111 tuple(e-s for s, e, _, _, _ in active), tuple(e-s for _, _, s, e, _ in active),
112 tuple(r for _, _, _, _, r in active),
113 )
116@lru_cache(maxsize=128)
117@torch.inference_mode(False)
118def _device_lengths(plan: CSATNDPlan, device: torch.device) -> tuple:
119 """Cache by the complete document partition, not merely by total Q/K sizes."""
120 cu_q = torch.tensor((0, *accumulate(plan.q_lengths)), device=device, dtype=torch.int32)
121 cu_k = torch.tensor((0, *accumulate(plan.k_lengths)), device=device, dtype=torch.int32)
122 residuals = torch.tensor(plan.residuals, device=device, dtype=torch.int32)
123 offsets = torch.tensor([s for s, _ in plan.k_ranges], device=device, dtype=torch.int32)
124 lengths = torch.tensor(plan.q_lengths, device=device, dtype=torch.int64)
125 offsets = torch.repeat_interleave(offsets, lengths, output_size=sum(plan.q_lengths)).unsqueeze(1)
126 return cu_q, cu_k, residuals, offsets
129@lru_cache(maxsize=1)
130def _load_attention_ops() -> tuple[Callable[..., Any], Callable[..., Any], Callable[..., Any]]:
131 """Resolve attention forward, backward and metadata through the official binding."""
132 # Lazy import leaves the eager baseline usable without the NPU extension.
133 try:
134 from cann_ops_transformer import ( # pylint: disable=import-outside-toplevel
135 sparse_flash_mla as sparse_flash_mla_op,
136 sparse_flash_mla_grad, sparse_flash_mla_metadata,
137 )
138 except ImportError as err:
139 raise RuntimeError(
140 "use_fused_ops=True requires cann_ops_transformer.sparse_flash_mla, sparse_flash_mla_grad "
141 "and sparse_flash_mla_metadata. "
142 "See hyper_parallel/components/functional/README.md for ops-transformer installation, "
143 "environment setup and tested versions."
144 ) from err
145 if (
146 callable(sparse_flash_mla_op)
147 and callable(sparse_flash_mla_grad)
148 and callable(sparse_flash_mla_metadata)
149 ):
150 namespace = torch.ops.cann_ops_transformer
151 ops = tuple(
152 getattr(namespace, name, None)
153 for name in ("sparse_flash_mla", "sparse_flash_mla_grad", "sparse_flash_mla_metadata")
154 )
155 if all(op is not None for op in ops):
156 return ops # type: ignore[return-value]
157 return sparse_flash_mla_op, sparse_flash_mla_grad, sparse_flash_mla_metadata
160@lru_cache(maxsize=1)
161def _load_attention_grad_metadata_op() -> Callable[..., Any]:
162 """Import the A5-only backward scheduling entry when it will be used."""
163 try:
164 from cann_ops_transformer import sparse_flash_mla_grad_metadata # pylint: disable=import-outside-toplevel
165 except ImportError as err:
166 raise RuntimeError(
167 "Ascend 950/A5 requires cann_ops_transformer.sparse_flash_mla_grad_metadata. "
168 "See hyper_parallel/components/functional/README.md for ops-transformer installation, "
169 "environment setup and tested versions."
170 ) from err
172 if callable(sparse_flash_mla_grad_metadata):
173 dispatcher_op = getattr(torch.ops.cann_ops_transformer, "sparse_flash_mla_grad_metadata", None)
174 if dispatcher_op is not None:
175 return dispatcher_op
177 return sparse_flash_mla_grad_metadata
180@lru_cache(maxsize=16)
181def _uses_attention_grad_metadata(device: torch.device) -> bool:
182 """Use backward scheduling metadata only on Ascend 950/A5.
184 The A5 backward kernel requires the dedicated metadata plan, while the
185 A2/A3 kernel contract accepts only None for the same argument.
186 """
187 device_name = torch.npu.get_device_name(device)
188 return any(marker in device_name for marker in _A5_DEVICE_MARKERS)
191def supports_fused_attention_inputs(query: torch.Tensor, ratio: int, window: int, topk: int = 512) -> bool:
192 """Check the validated attention input contract without importing operators.
194 Args:
195 query: Main Q [batch, heads, queries, dimension].
196 ratio: Model ratio, zero for a pure SWA layer.
197 window: Raw attention window, including the current token.
198 topk: Logical compressed selection width, before padding; zero means no complete compressed key.
199 """
200 if query.device.type != "npu" or query.dtype != torch.bfloat16:
201 return False
202 if query.shape[-1] != 512 or window != 128 or ratio not in (0, 1, 2):
203 return False
204 if query.shape[1] not in (1, 2, 4, 8, 16, 32, 64, 128) or query.shape[2] == 0:
205 return False
206 if ratio and not 0 <= topk <= 512:
207 return False
208 return True
211@lru_cache(maxsize=128)
212@torch.inference_mode(False)
213def _attention_metadata(
214 device: torch.device, batch: int, length: int, heads: int, dim: int,
215 raw_length: int, main_length: int, topk: int, ratio: int, residual: int, window: int,
216) -> tuple:
217 """Reuse shape metadata across evaluation and gradient-tracked training.
219 Evaluation may populate the cache under inference_mode. The backward
220 saves the cached residual, so it must be an ordinary tensor regardless
221 of which mode first populated the cache.
222 """
223 # The training backward requires a zero residual tensor even at ratio one;
224 # the forward interface instead omits that optional input at ratio one.
225 residue = torch.full((batch,), residual, dtype=torch.int32, device=device) if main_length else None
226 _, _, metadata_op = _load_attention_ops()
227 metadata_args = (heads, 1, dim)
228 metadata_kwargs = {
229 "cmp_residual_kv": residue if ratio > 1 else None, "batch_size": batch, "max_seqlen_q": length,
230 "max_seqlen_ori_kv": raw_length, "max_seqlen_cmp_kv": main_length, "ori_topk": 0, "cmp_topk": topk,
231 "cmp_ratio": ratio, "ori_mask_mode": 4,
232 "cmp_mask_mode": 3 if main_length else 0,
233 "ori_win_left": window-1, "ori_win_right": 0,
234 "layout_q": "BSND", "layout_kv": "BSND", "has_ori_kv": True, "has_cmp_kv": bool(main_length),
235 }
236 metadata = metadata_op(*metadata_args, **metadata_kwargs)
237 grad_metadata = None
238 if _uses_attention_grad_metadata(device):
239 grad_metadata = _load_attention_grad_metadata_op()(*metadata_args, **metadata_kwargs)
240 return residue, metadata, grad_metadata
243class _SparseFlashMla(torch.autograd.Function):
244 """Wrap SparseFlashMla and SparseFlashMlaGrad without substituting the KL teacher."""
246 @staticmethod
247 def forward(
248 ctx: Any, query: torch.Tensor, raw: torch.Tensor, main: torch.Tensor | None,
249 indices: torch.Tensor | None, sinks: torch.Tensor, scale: float,
250 ratio: int, residual: int, window: int,
251 ) -> torch.Tensor:
252 """Save the native output and LSE required by the training backward."""
253 batch, length, heads, dim = query.shape
254 residue, metadata, grad_metadata = _attention_metadata(
255 query.device, batch, length, heads, dim, raw.shape[1], 0 if main is None else main.shape[1],
256 0 if indices is None else indices.shape[-1], ratio, residual, window,
257 )
258 options = {"softmax_scale": scale, "cmp_ratio": ratio, "ori_mask_mode": 4,
259 "cmp_mask_mode": 3 if main is not None else 0,
260 "ori_win_left": window-1, "ori_win_right": 0, "layout_q": "BSND", "layout_kv": "BSND"}
261 attention, _, _ = _load_attention_ops()
262 output, lse = attention(
263 query, ori_kv=raw, cmp_kv=main, cmp_sparse_indices=indices, sinks=sinks,
264 cmp_residual_kv=residue if ratio > 1 else None, metadata=metadata, return_softmax_lse=True, **options,
265 )
266 ctx.save_for_backward(query, raw, main, indices, sinks, residue, output, lse, grad_metadata)
267 ctx.options = options
268 return output
270 @staticmethod
271 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
272 """Return main-branch gradients without substituting the KL teacher."""
273 query, raw, main, indices, sinks, residue, output, lse, grad_metadata = ctx.saved_tensors
274 _, attention_grad, _ = _load_attention_ops()
275 grad_query, grad_raw, grad_main, grad_sinks, _, _ = attention_grad(
276 query, grad_output.contiguous(), output, lse, ori_kv=raw, cmp_kv=main,
277 cmp_sparse_indices=indices, sinks=sinks, cmp_residual_kv=residue,
278 metadata=grad_metadata, **ctx.options,
279 )
280 return grad_query, grad_raw, grad_main if main is not None else None, None, grad_sinks, None, None, None, None
283def _bsnd_sparse_flash_mla(
284 query: torch.Tensor, raw_key: torch.Tensor, main_key: torch.Tensor | None,
285 indices: torch.Tensor | None, sinks: torch.Tensor, scale: float, ratio: int,
286 window: int, query_offset: int,
287 segment: tuple[int, int, int, int, int], raw_key_offset: int = 0, main_key_offset: int = 0,
288 raw_document_starts: tuple = (),
289) -> torch.Tensor:
290 """Run one document segment per batch item with independently routed KV banks.
292 The operator owns Q tiling within this BSND call. Multiple packed
293 documents use the TND entry with cumulative document lengths.
295 Args:
296 query: Local attention Q in [B, H, Q, D].
297 raw_key: Full or halo raw KV in [B, 1, K, D].
298 main_key: Full or prefix compressed KV in [B, Kc, D], or None for SWA only.
299 indices: Global compressed selection [B, Q, topk], invalid slots -1.
300 sinks: One scalar logit per head.
301 scale: Attention dot-product scale.
302 ratio: Compression ratio, zero denotes the SWA-only layer.
303 window: Number of raw tokens visible to each query including itself.
304 query_offset: Global position of the first local query.
305 segment: Local Q start/end, compressed document start/prefix end and residual,
306 shared by all physical batch items.
308 Returns:
309 Attention output in [B, Q, H, D].
310 """
311 if query.dtype != torch.bfloat16 or query.shape[-1] != 512 or window != 128:
312 raise ValueError("V4 attention requires BF16, head_dim=512, and window=128")
313 start, end, key_start, key_end, residual = segment
314 document_start = dict(raw_document_starts).get(start, key_start * max(ratio, 1))
315 raw_left = max(document_start, query_offset + start - window + 1)
316 raw_right = query_offset + end
317 # contiguous() may keep stale singleton strides after slicing a BSND KV bank.
318 batch, _, _, dim = query.shape
319 raw = raw_key[:, :, raw_left-raw_key_offset:raw_right-raw_key_offset]
320 raw = raw.squeeze(1).contiguous().view(batch, raw_right-raw_left, 1, dim)
321 main = None
322 selected = None
323 if ratio and key_end > key_start:
324 main = main_key[:, key_start-main_key_offset:key_end-main_key_offset]
325 main = main.contiguous().view(batch, key_end-key_start, 1, dim)
326 original = indices[:, start:end]
327 selected = torch.where(original >= 0, original-key_start, -1).int()
328 # Backward infers the active count from this width and causality; only KL requires 512 slots.
329 selected = selected.unsqueeze(2).contiguous()
330 return _SparseFlashMla.apply(
331 query[:, :, start:end].transpose(1, 2).contiguous(), raw, main, selected, sinks.float(),
332 scale, max(ratio, 1) if main is not None else 1, residual if main is not None else 0, window,
333 )
336@lru_cache(maxsize=128)
337@torch.inference_mode(False)
338def _tnd_attention_metadata(plan, device, heads, dim, raw_ranges, ratio, window, has_keys, topk):
339 """Describe independent raw and compressed coordinate systems to SMLA."""
340 cu_q, cu_k, residuals, _ = plan.lengths(device)
341 raw_lengths = tuple(end-start for start, end in raw_ranges)
342 cu_raw = torch.tensor((0, *accumulate(raw_lengths)), device=device, dtype=torch.int32)
343 _, _, metadata_op = _load_attention_ops()
344 options = {"layout_q": "TND", "layout_kv": "TND", "cmp_ratio": ratio, "ori_mask_mode": 4,
345 "cmp_mask_mode": 3 if has_keys else 0, "ori_win_left": window-1, "ori_win_right": 0}
346 metadata_args = (heads, 1, dim)
347 metadata_kwargs = {
348 "cu_seqlens_q": cu_q, "cu_seqlens_ori_kv": cu_raw,
349 "cu_seqlens_cmp_kv": cu_k if has_keys else None,
350 "cmp_residual_kv": residuals if has_keys and ratio > 1 else None,
351 "batch_size": len(plan.segments), "max_seqlen_q": max(plan.q_lengths),
352 "max_seqlen_ori_kv": max(raw_lengths), "max_seqlen_cmp_kv": max(plan.k_lengths) if has_keys else 0,
353 "ori_topk": 0, "cmp_topk": topk, "has_ori_kv": True, "has_cmp_kv": has_keys, **options,
354 }
355 metadata = metadata_op(*metadata_args, **metadata_kwargs)
356 grad_metadata = None
357 if _uses_attention_grad_metadata(device):
358 grad_metadata = _load_attention_grad_metadata_op()(*metadata_args, **metadata_kwargs)
359 return cu_q, cu_raw, cu_k if has_keys else None, residuals if has_keys else None, metadata, grad_metadata
362class _SparseFlashMlaTND(torch.autograd.Function):
363 """Native multi-document forward/backward; save all sequence tensors through autograd."""
365 @staticmethod
366 def forward(
367 ctx: Any, query: torch.Tensor, raw: torch.Tensor, main: torch.Tensor | None,
368 indices: torch.Tensor | None, sinks: torch.Tensor, scale: float, ratio: int, window: int,
369 plan: CSATNDPlan, raw_ranges: tuple,
370 ) -> torch.Tensor:
371 """Save native output/LSE and independent raw/compressed cumulative lengths."""
372 cu_q, cu_raw, cu_k, residuals, metadata, grad_metadata = _tnd_attention_metadata(
373 plan, query.device, query.shape[1], query.shape[2], raw_ranges, ratio, window, main is not None,
374 0 if indices is None else indices.shape[-1],
375 )
376 options = {"layout_q": "TND", "layout_kv": "TND", "softmax_scale": scale, "cmp_ratio": ratio,
377 "ori_mask_mode": 4, "cmp_mask_mode": 3 if main is not None else 0,
378 "ori_win_left": window-1, "ori_win_right": 0}
379 forward, _, _ = _load_attention_ops()
380 output, lse = forward(
381 query, ori_kv=raw, cmp_kv=main, cmp_sparse_indices=indices, sinks=sinks,
382 cu_seqlens_q=cu_q, cu_seqlens_ori_kv=cu_raw, cu_seqlens_cmp_kv=cu_k,
383 cmp_residual_kv=residuals if ratio > 1 else None, metadata=metadata,
384 return_softmax_lse=True, **options,
385 )
386 ctx.save_for_backward(query, raw, main, indices, sinks, output, lse, cu_q, cu_raw, cu_k, residuals,
387 grad_metadata)
388 ctx.options = options
389 return output
391 @staticmethod
392 def backward(ctx: Any, grad_output: torch.Tensor) -> tuple:
393 """Return each physical bank's gradient to its autograd communication owner."""
394 query, raw, main, indices, sinks, output, lse, cu_q, cu_raw, cu_k, residuals, grad_metadata = ctx.saved_tensors
395 _, backward, _ = _load_attention_ops()
396 dq, dr, dm, ds, _, _ = backward(
397 query, grad_output.contiguous(), output, lse, ori_kv=raw, cmp_kv=main,
398 cmp_sparse_indices=indices, sinks=sinks, cu_seqlens_q=cu_q, cu_seqlens_ori_kv=cu_raw,
399 cu_seqlens_cmp_kv=cu_k, cmp_residual_kv=residuals, metadata=grad_metadata, **ctx.options,
400 )
401 return dq, dr, dm if main is not None else None, None, ds, None, None, None, None, None
404def sparse_flash_mla(
405 query: torch.Tensor, raw_key: torch.Tensor, main_key: torch.Tensor | None,
406 indices: torch.Tensor | None, sinks: torch.Tensor, scale: float, ratio: int,
407 window: int, query_offset: int, segments: tuple, raw_key_offset: int = 0, main_key_offset: int = 0,
408 raw_document_starts: tuple = (),
409) -> torch.Tensor:
410 """Batch packed documents in native TND with independently routed KV banks.
412 Args:
413 query: Local attention Q [batch, heads, queries, 512].
414 raw_key: Full or halo raw KV [batch, 1, keys, 512].
415 main_key: Full or document-prefix compressed KV [batch, compressed keys, 512], or None.
416 indices: Sorted global compressed key IDs, invalid slots -1.
417 sinks: Per-head scalar sink logits.
418 scale: Attention dot-product scale.
419 ratio: Compression ratio; zero selects pure SWA.
420 window: Raw sliding-window size, including the current token.
421 query_offset: Global position of the first local query.
422 segments: Local Q start/end, compressed document start/prefix end and residual.
423 raw_document_starts: Explicit (local Q start, raw document start) pairs for natural lengths.
424 raw_key_offset: Global position of the first row in the compact raw KV bank.
425 main_key_offset: Global compressed ID represented by row zero of main_key.
427 Returns:
428 Attention output [batch, queries, heads, 512]. A single document or
429 ordinary physical batch uses BSND. Empty compressed prefixes form a
430 separate SWA-only TND group without inventing compressed keys.
431 """
432 if len(segments) == 1:
433 return _bsnd_sparse_flash_mla(
434 query, raw_key, main_key, indices, sinks, scale, ratio, window, query_offset, segments[0],
435 raw_key_offset, main_key_offset, raw_document_starts,
436 )
437 if query.shape[0] != 1:
438 raise ValueError("Packed Sparse Flash MLA requires batch size one")
439 if query.dtype != torch.bfloat16 or query.shape[-1] != 512 or window != 128:
440 raise ValueError("V4 attention requires BF16, head_dim=512, and window=128")
441 document_starts = dict(raw_document_starts)
442 output = None
443 for has_keys in (True, False):
444 plan = csa_tnd_plan(segments, ratio, has_keys)
445 if plan is None:
446 continue
447 raw_ranges = tuple(
448 (max(document_starts.get(s, ks * max(ratio, 1)), query_offset+s-window+1)-raw_key_offset,
449 query_offset+e-raw_key_offset)
450 for s, e, ks, _, _ in plan.segments
451 )
452 raw = pack_ranges(raw_key.squeeze(0).squeeze(0), raw_ranges).unsqueeze(1)
453 main = plan.key(main_key, main_key_offset).unsqueeze(1) if has_keys else None
454 selected = plan.local_indices(indices) if has_keys else None
455 part = _SparseFlashMlaTND.apply(
456 plan.query(query.transpose(1, 2)), raw, main, selected, sinks.float(),
457 scale, max(ratio, 1) if has_keys else 1, window, plan, raw_ranges,
458 )
459 # A complete Q partition is already ordered; a canvas would retain another full output.
460 if plan.covers_queries(query.shape[2]):
461 return part.unsqueeze(0)
462 if output is None:
463 output = torch.zeros_like(query.transpose(1, 2))
464 plan.restore(part, output)
465 return torch.zeros_like(query.transpose(1, 2)) if output is None else output