File size: 2,246 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""Public-library sparse baselines. All index-dependent GPU work is timed."""

from functools import lru_cache

import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
from torch.nn.attention.flex_attention import BlockMask, flex_attention


NAMES = {
    "block_sparse_gqa": "torch2.9.1/FlexAttention/block-sparse/GQA/compiled",
    "sparse_mla": "GPU gather + SDPA EFFICIENT_ATTENTION/absorbed-MLA (composed; not FlashMLA)",
}


@lru_cache(maxsize=1)
def compiled_flex():
    return torch.compile(flex_attention, fullgraph=True, mode="max-autotune-no-cudagraphs")


def block_sparse_gqa(q, k, v, block_counts, block_indices, block_size, causal):
    shift = k.shape[-2] - q.shape[-2]

    def mask(batch, head, qi, ki):
        return qi + shift >= ki

    blocks = BlockMask.from_kv_blocks(
        block_counts[:, None], block_indices[:, None], BLOCK_SIZE=block_size,
        seq_lengths=(q.shape[-2], k.shape[-2]), compute_q_blocks=False,
        mask_mod=mask if causal else None,
    )
    # In 2.9.1 the automatic short-query decoding path fails our per-Q-block
    # causal fixture. Force the general sparse forward path, validated below.
    return compiled_flex()(q, k, v, block_mask=blocks, enable_gqa=True,
                           kernel_options={"FORCE_USE_FLEX_ATTENTION": True})


def sparse_mla(q, cache, indices, latent_dim, scale):
    b, nq, h, d = q.shape
    valid = indices >= 0
    selected = cache.flatten(0, 1)[indices.clamp_min(0).long()].reshape(b * nq, 1, -1, d)
    # Treat query heads as the query length: every head uses this row's same KV list.
    query = q.reshape(b * nq, 1, h, d)
    bias = torch.where(valid.reshape(b * nq, 1, 1, -1), 0., -torch.inf).to(q.dtype)
    # CUTLASS requires aligned bias strides even when the logical top-k has a tail.
    slots = indices.shape[-1]
    bias = F.pad(bias, (0, (-slots) % 8), value=-torch.inf)[..., :slots]
    with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
        out = F.scaled_dot_product_attention(query, selected, selected[..., :latent_dim],
                                            attn_mask=bias, scale=scale)
    return torch.where(valid.any(-1)[..., None, None], out.reshape(b, nq, h, latent_dim), 0.)