File size: 9,057 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""H100 block_sparse_gqa. Adapted from public-trial gpt6-astra-h100-xhigh-c2-20261105, frozen submission 4533473a1cb69f9c5d8c8302183d177c04b3819c91d215cd08222c39e24339e8."""
import math

import torch
import triton as tr
import triton.language as tl


def _attention_configs():
    configurations = []
    for bm, bn, warps, stages in [
        (16, 64, 4, 1),
        (16, 64, 4, 2),
        (16, 128, 4, 2),
        (16, 256, 4, 1),
        (32, 64, 4, 2),
        (32, 64, 4, 3),
        (32, 128, 4, 1),
        (32, 128, 4, 2),
        (32, 128, 4, 3),
        (32, 256, 4, 1),
        (32, 256, 8, 1),
        (64, 64, 4, 2),
        (64, 64, 4, 3),
        (64, 128, 4, 1),
        (64, 128, 4, 2),
        (64, 128, 4, 3),
        (64, 128, 8, 2),
        (64, 256, 8, 1),
        (64, 256, 8, 2),
        (128, 64, 4, 1),
        (128, 64, 4, 2),
        (128, 64, 4, 3),
        (128, 64, 8, 2),
        (128, 128, 4, 1),
        (128, 128, 8, 2),
    ]:
        configurations.append(
            tr.Config(
                {"BM": bm, "BN": bn, "PIPE": stages, "MODE": 0},
                num_warps=warps,
                num_stages=stages,
            )
        )
    # Scalar block traversal can avoid entire masked blocks in short,
    # strongly causal attention.
    for bm, bn in [(32, 64), (32, 128), (64, 64), (64, 128)]:
        configurations.append(
            tr.Config(
                {"BM": bm, "BN": bn, "PIPE": 2, "MODE": 1},
                num_warps=4,
                num_stages=2,
            )
        )
    return configurations


def _prune_attention_configs(configs, named_args, **kwargs):
    args = dict(named_args)
    args.update(kwargs)
    bs = args["BS"]
    bd = args["BD"]
    max_bm = max(16, tr.next_power_of_2(bs))
    result = []
    for config in configs:
        bm = config.kwargs["BM"]
        bn = config.kwargs["BN"]
        stages = config.kwargs["PIPE"]
        mode = config.kwargs["MODE"]
        if bm > max_bm:
            continue
        if mode == 1 and bn > max(64, tr.next_power_of_2(bs)):
            continue
        estimated_shared = 2 * bm * bd + 4 * bn * bd * stages
        if estimated_shared > 225280:
            continue
        result.append(config)
    return result if result else configs[:1]


@tr.jit
def _attention_update(
    q, KP, VP, cols, col_valid, rows, row_valid, ds,
    acc, m, l,
    QLEN: tl.constexpr, KLEN: tl.constexpr, DIM: tl.constexpr,
    ks2: tl.constexpr, ks3: tl.constexpr,
    vs2: tl.constexpr, vs3: tl.constexpr,
    CAUSAL: tl.constexpr, SCALE: tl.constexpr,
):
    keys = tl.load(
        KP + ds[:, None] * ks3 + cols[None, :] * ks2,
        mask=(ds[:, None] < DIM) & col_valid[None, :],
        other=0,
    )
    scores = tl.dot(q, keys) * SCALE
    valid = row_valid[:, None] & col_valid[None, :]
    if CAUSAL:
        valid = valid & (cols[None, :] <= rows[:, None] + KLEN - QLEN)
    scores = tl.where(valid, scores, -float("inf"))

    new_m = tl.maximum(m, tl.max(scores, 1))
    safe_m = tl.where(new_m == -float("inf"), 0.0, new_m)
    alpha = tl.exp2(m - safe_m)
    p = tl.exp2(scores - safe_m[:, None])
    new_l = l * alpha + tl.sum(p, 1)
    acc = acc * alpha[:, None]

    values = tl.load(
        VP + cols[:, None] * vs2 + ds[None, :] * vs3,
        mask=col_valid[:, None] & (ds[None, :] < DIM),
        other=0,
    )
    acc = tl.dot(p.to(q.dtype), values, acc)
    return acc, new_m, new_l


@tr.autotune(
    configs=_attention_configs(),
    key=[
        "BATCH", "HEADS", "GROUP", "QLEN", "KLEN", "DIM",
        "BS", "MAX_BLOCKS", "CAUSAL",
        "qs2", "ks2", "vs2", "chdiv", "ihdiv",
    ],
    prune_configs_by={"early_config_prune": _prune_attention_configs},
    use_cuda_graph=True,
)
@tr.jit
def _block_attention(
    Q, K, V, Counts, Indices, O,
    BATCH: tl.constexpr,
    QLEN: tl.constexpr, KLEN: tl.constexpr,
    HEADS: tl.constexpr, GROUP: tl.constexpr, DIM: tl.constexpr,
    BS: tl.constexpr, MAX_BLOCKS: tl.constexpr, BD: tl.constexpr,
    CAUSAL: tl.constexpr, SCALE: tl.constexpr,
    qs0: tl.constexpr, qs1: tl.constexpr, qs2: tl.constexpr, qs3: tl.constexpr,
    ks0: tl.constexpr, ks1: tl.constexpr, ks2: tl.constexpr, ks3: tl.constexpr,
    vs0: tl.constexpr, vs1: tl.constexpr, vs2: tl.constexpr, vs3: tl.constexpr,
    csb: tl.constexpr, csh: tl.constexpr, csr: tl.constexpr, chdiv: tl.constexpr,
    isb: tl.constexpr, ish: tl.constexpr, isr: tl.constexpr,
    iss: tl.constexpr, ihdiv: tl.constexpr,
    BM: tl.constexpr, BN: tl.constexpr, PIPE: tl.constexpr, MODE: tl.constexpr,
):
    tile = tl.program_id(0)
    bh = tl.program_id(1)
    b = bh // HEADS
    h = bh % HEADS
    kh = h // GROUP

    tiles_per_block: tl.constexpr = tr.cdiv(BS, BM)
    qb = tile // tiles_per_block
    start = qb * BS + (tile % tiles_per_block) * BM
    rows = start + tl.arange(0, BM)
    ds = tl.arange(0, BD)
    ns = tl.arange(0, BN)
    row_valid = (rows < QLEN) & (rows < (qb + 1) * BS)

    count = tl.load(Counts + b * csb + (h // chdiv) * csh + qb * csr)
    ip = Indices + b * isb + (h // ihdiv) * ish + qb * isr
    kp = K + b * ks0 + kh * ks1
    vp = V + b * vs0 + kh * vs1

    acc = tl.full((BM, BD), 0.0, tl.float32)
    m = tl.full((BM,), -float("inf"), tl.float32)
    l = tl.full((BM,), 0.0, tl.float32)

    if count > 0:
        q = tl.load(
            Q + b * qs0 + h * qs1 + rows[:, None] * qs2 + ds[None, :] * qs3,
            mask=row_valid[:, None] & (ds[None, :] < DIM),
            other=0,
        )

        if MODE == 0:
            # A tile may cover several selected blocks. Selection remains
            # entirely GPU-driven, including the partially occupied final tile.
            iterations = tl.cdiv(count * BS, BN)
            for step in tl.range(0, iterations, num_stages=PIPE):
                logical = step * BN + ns
                slots = logical // BS
                within = logical % BS
                ids = tl.load(ip + slots * iss, mask=slots < count, other=0)
                cols = ids * BS + within
                col_valid = (slots < count) & (cols >= 0) & (cols < KLEN)
                acc, m, l = _attention_update(
                    q, kp, vp, cols, col_valid, rows, row_valid, ds,
                    acc, m, l,
                    QLEN, KLEN, DIM, ks2, ks3, vs2, vs3, CAUSAL, SCALE,
                )
        else:
            for block in range(count):
                bid = tl.load(ip + block * iss)
                base = bid * BS
                useful = base < KLEN
                if CAUSAL:
                    useful = useful & (
                        base <= tl.minimum(start + BM - 1, QLEN - 1) + KLEN - QLEN
                    )
                if useful:
                    for sub in tl.static_range(tr.cdiv(BS, BN)):
                        within = sub * BN + ns
                        cols = base + within
                        col_valid = (within < BS) & (cols >= 0) & (cols < KLEN)
                        acc, m, l = _attention_update(
                            q, kp, vp, cols, col_valid, rows, row_valid, ds,
                            acc, m, l,
                            QLEN, KLEN, DIM, ks2, ks3, vs2, vs3, CAUSAL, SCALE,
                        )

    result = acc / tl.where(l > 0.0, l, 1.0)[:, None]
    tl.store(
        O + (bh * QLEN + rows[:, None]) * DIM + ds[None, :],
        result,
        mask=row_valid[:, None] & (ds[None, :] < DIM),
    )


def _direct(q, k, v, block_counts, block_indices, block_size, causal):
    batch, heads, q_len, dim = q.shape
    out = q.new_empty(q.shape)
    def grid(meta):
        bm = meta["BM"]
        tiles = (q_len // block_size) * tr.cdiv(block_size, bm) + tr.cdiv(q_len % block_size, bm)
        return tiles, batch * heads
    _block_attention[grid](
        q, k, v, block_counts, block_indices, out,
        BATCH=batch, QLEN=q_len, KLEN=k.size(2), HEADS=heads, GROUP=heads // k.size(1),
        DIM=dim, BS=block_size, MAX_BLOCKS=block_indices.size(-1),
        BD=max(16, tr.next_power_of_2(dim)), CAUSAL=causal, SCALE=math.log2(math.e) / math.sqrt(dim),
        qs0=q.stride(0), qs1=q.stride(1), qs2=q.stride(2), qs3=q.stride(3),
        ks0=k.stride(0), ks1=k.stride(1), ks2=k.stride(2), ks3=k.stride(3),
        vs0=v.stride(0), vs1=v.stride(1), vs2=v.stride(2), vs3=v.stride(3),
        csb=block_counts.stride(0), csh=0, csr=block_counts.stride(1), chdiv=1,
        isb=block_indices.stride(0), ish=0, isr=block_indices.stride(1),
        iss=block_indices.stride(2), ihdiv=1)
    return out


def block_sparse_gqa(q, k, v, block_counts, block_indices, block_size, causal):
    from kernel_bench.baseline_v06.sparse_plan import pick_backend
    from kernel_bench.sparse_baselines import block_sparse_gqa as flex
    args = (q, k, v, block_counts, block_indices, block_size, causal)
    # The masked compact-head, noncausal path is already efficient in FlexAttention.
    if not causal and q.shape[-1] <= 64:
        return flex(*args)
    use_direct = pick_backend(_direct, flex, args)
    return (_direct if use_direct else flex)(*args)