flash_attn_interface.py 21 KB
Newer Older
Tri Dao's avatar
Tri Dao committed
1
2
import torch
import torch.nn as nn
3
import torch.nn.functional as F
Tri Dao's avatar
Tri Dao committed
4

Tri Dao's avatar
Tri Dao committed
5
import flash_attn_cuda
Tri Dao's avatar
Tri Dao committed
6
7


Tri Dao's avatar
Tri Dao committed
8
def _get_block_size(device, head_dim, is_dropout):
9
10
    assert head_dim % 8 == 0 and head_dim <= 128
    return 256 if head_dim <= 64 else 128
Tri Dao's avatar
Tri Dao committed
11
12


13
def _flash_attn_forward(q, k, v, out, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
Tri Dao's avatar
Tri Dao committed
14
15
16
17
18
19
20
                        dropout_p, softmax_scale, causal, return_softmax, num_splits=0,
                        generator=None):
    """
    num_splits: how much to parallelize over the seqlen_q dimension. num_splits=0 means
    it will be set by an internal heuristic. We're exposing num_splits mostly for benchmarking.
    Don't change it unless you know what you're doing.
    """
21
22
    softmax_lse, *rest = flash_attn_cuda.fwd(
        q, k, v, out, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p,
Tri Dao's avatar
Tri Dao committed
23
        softmax_scale, False, causal, return_softmax, num_splits, generator
Tri Dao's avatar
Tri Dao committed
24
25
    )
    # if out.isnan().any() or softmax_lse.isnan().any():
Tri Dao's avatar
Tri Dao committed
26
27
    #     breakpoint()
    S_dmask = rest[0] if return_softmax else None
Tri Dao's avatar
Tri Dao committed
28
    return out, softmax_lse, S_dmask
Tri Dao's avatar
Tri Dao committed
29
30


Tri Dao's avatar
Tri Dao committed
31
def _flash_attn_backward(dout, q, k, v, out, softmax_lse, dq, dk, dv, cu_seqlens_q, cu_seqlens_k,
Tri Dao's avatar
Tri Dao committed
32
                         max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale, causal, num_splits=0,
33
                         generator=None):
Tri Dao's avatar
Tri Dao committed
34
    """
35
36
37
38
    num_splits: whether to parallelize over the seqlen_k dimension (num_splits > 1) or
    not (num_splits = 1). num_splits=0 means it will be set by an internal heuristic.
    Any value above 1 will call the same kernel (i.e. num_splits=2 would call the same kernel
    as num_splits=3), so effectively the choices are 0, 1, and 2.
Tri Dao's avatar
Tri Dao committed
39
40
    This hyperparameter can be tuned for performance, but default value (heuristic) should work fine.
    """
41
    dout = dout.contiguous()  # CUDA code assumes that dout is contiguous
42
    _, _, _, softmax_d = flash_attn_cuda.bwd(
Tri Dao's avatar
Tri Dao committed
43
        dout, q, k, v, out, softmax_lse, dq, dk, dv, cu_seqlens_q, cu_seqlens_k,
Tri Dao's avatar
Tri Dao committed
44
        max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale, False, causal, num_splits, generator)
Tri Dao's avatar
Tri Dao committed
45
    # if dk.isnan().any() or dk.isnan().any() or dv.isnan().any() or softmax_d.isnan().any():
Tri Dao's avatar
Tri Dao committed
46
    #     breakpoint()
Tri Dao's avatar
Tri Dao committed
47
    return dq, dk, dv, softmax_d
Tri Dao's avatar
Tri Dao committed
48
49


Tri Dao's avatar
Tri Dao committed
50
class FlashAttnQKVPackedFunc(torch.autograd.Function):
Tri Dao's avatar
Tri Dao committed
51
52

    @staticmethod
53
54
    def forward(ctx, qkv, cu_seqlens, max_seqlen, dropout_p, softmax_scale, causal,
                return_softmax, deterministic):
Tri Dao's avatar
Tri Dao committed
55
56
57
58
        # Save rng_state because the backward pass will regenerate the dropout mask
        rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None
        if softmax_scale is None:
            softmax_scale = qkv.shape[-1] ** (-0.5)
Tri Dao's avatar
Tri Dao committed
59
        out, softmax_lse, S_dmask = _flash_attn_forward(
60
61
62
            qkv[:, 0], qkv[:, 1], qkv[:, 2], torch.empty_like(qkv[:, 0]), cu_seqlens, cu_seqlens,
            max_seqlen, max_seqlen, dropout_p, softmax_scale, causal=causal,
            return_softmax=return_softmax
Tri Dao's avatar
Tri Dao committed
63
        )
Tri Dao's avatar
Tri Dao committed
64
        ctx.save_for_backward(qkv, out, softmax_lse, cu_seqlens, rng_state)
Tri Dao's avatar
Tri Dao committed
65
        ctx.dropout_p = dropout_p
Tri Dao's avatar
Tri Dao committed
66
        ctx.max_seqlen = max_seqlen
Tri Dao's avatar
Tri Dao committed
67
68
        ctx.softmax_scale = softmax_scale
        ctx.causal = causal
69
        ctx.deterministic = deterministic
Tri Dao's avatar
Tri Dao committed
70
        return out if not return_softmax else (out, softmax_lse, S_dmask)
Tri Dao's avatar
Tri Dao committed
71
72

    @staticmethod
Tri Dao's avatar
Tri Dao committed
73
74
    def backward(ctx, dout, *args):
        qkv, out, softmax_lse, cu_seqlens, rng_state = ctx.saved_tensors
Tri Dao's avatar
Tri Dao committed
75
76
77
        if rng_state is not None:
            cur_rng_state = torch.cuda.get_rng_state()
            torch.cuda.set_rng_state(rng_state)
Tri Dao's avatar
Tri Dao committed
78
79
80
81
        dqkv = torch.empty_like(qkv)
        _flash_attn_backward(
            dout, qkv[:, 0], qkv[:, 1], qkv[:, 2], out, softmax_lse,
            dqkv[:, 0], dqkv[:, 1], dqkv[:, 2], cu_seqlens, cu_seqlens,
82
83
            ctx.max_seqlen, ctx.max_seqlen, ctx.dropout_p, ctx.softmax_scale, ctx.causal,
            num_splits=1 if ctx.deterministic else 0,
Tri Dao's avatar
Tri Dao committed
84
85
86
        )
        if rng_state is not None:
            torch.cuda.set_rng_state(cur_rng_state)
87
        return dqkv, None, None, None, None, None, None, None
Tri Dao's avatar
Tri Dao committed
88
89


Tri Dao's avatar
Tri Dao committed
90
class FlashAttnKVPackedFunc(torch.autograd.Function):
Tri Dao's avatar
Tri Dao committed
91
92

    @staticmethod
Tri Dao's avatar
Tri Dao committed
93
    def forward(ctx, q, kv, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p,
94
                softmax_scale, causal, return_softmax, deterministic):
Tri Dao's avatar
Tri Dao committed
95
        # Save rng_state because the backward pass will regenerate the dropout mask
Tri Dao's avatar
Tri Dao committed
96
97
        rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None
        if softmax_scale is None:
Tri Dao's avatar
Tri Dao committed
98
99
            softmax_scale = q.shape[-1] ** (-0.5)
        out, softmax_lse, S_dmask = _flash_attn_forward(
100
101
            q, kv[:, 0], kv[:, 1], torch.empty_like(q), cu_seqlens_q, cu_seqlens_k, max_seqlen_q,
            max_seqlen_k, dropout_p, softmax_scale, causal=causal, return_softmax=return_softmax
Tri Dao's avatar
Tri Dao committed
102
103
104
105
106
107
108
        )
        ctx.save_for_backward(q, kv, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state)
        ctx.dropout_p = dropout_p
        ctx.max_seqlen_q = max_seqlen_q
        ctx.max_seqlen_k = max_seqlen_k
        ctx.softmax_scale = softmax_scale
        ctx.causal = causal
109
        ctx.deterministic = deterministic
Tri Dao's avatar
Tri Dao committed
110
111
112
113
114
115
116
117
118
119
120
121
122
        return out if not return_softmax else (out, softmax_lse, S_dmask)

    @staticmethod
    def backward(ctx, dout, *args):
        q, kv, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
        if rng_state is not None:
            cur_rng_state = torch.cuda.get_rng_state()
            torch.cuda.set_rng_state(rng_state)
        dq = torch.empty_like(q)
        dkv = torch.empty_like(kv)
        _flash_attn_backward(
            dout, q, kv[:, 0], kv[:, 1], out, softmax_lse,
            dq, dkv[:, 0], dkv[:, 1], cu_seqlens_q, cu_seqlens_k,
123
124
            ctx.max_seqlen_q, ctx.max_seqlen_k, ctx.dropout_p, ctx.softmax_scale, ctx.causal,
            num_splits=1 if ctx.deterministic else 0,
Tri Dao's avatar
Tri Dao committed
125
126
127
        )
        if rng_state is not None:
            torch.cuda.set_rng_state(cur_rng_state)
128
        return dq, dkv, None, None, None, None, None, None, None, None, None
Tri Dao's avatar
Tri Dao committed
129
130
131
132
133
134


class FlashAttnFunc(torch.autograd.Function):

    @staticmethod
    def forward(ctx, q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p,
135
                softmax_scale, causal, return_softmax, deterministic):
Tri Dao's avatar
Tri Dao committed
136
137
138
139
140
        # Save rng_state because the backward pass will regenerate the dropout mask
        rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None
        if softmax_scale is None:
            softmax_scale = q.shape[-1] ** (-0.5)
        out, softmax_lse, S_dmask = _flash_attn_forward(
141
            q, k, v, torch.empty_like(q), cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
Tri Dao's avatar
Tri Dao committed
142
            dropout_p, softmax_scale, causal=causal, return_softmax=return_softmax
Tri Dao's avatar
Tri Dao committed
143
        )
Tri Dao's avatar
Tri Dao committed
144
        ctx.save_for_backward(q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state)
Tri Dao's avatar
Tri Dao committed
145
        ctx.dropout_p = dropout_p
Tri Dao's avatar
Tri Dao committed
146
147
        ctx.max_seqlen_q = max_seqlen_q
        ctx.max_seqlen_k = max_seqlen_k
Tri Dao's avatar
Tri Dao committed
148
149
        ctx.softmax_scale = softmax_scale
        ctx.causal = causal
150
        ctx.deterministic = deterministic
Tri Dao's avatar
Tri Dao committed
151
        return out if not return_softmax else (out, softmax_lse, S_dmask)
Tri Dao's avatar
Tri Dao committed
152
153

    @staticmethod
Tri Dao's avatar
Tri Dao committed
154
155
    def backward(ctx, dout, *args):
        q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors
Tri Dao's avatar
Tri Dao committed
156
157
158
        if rng_state is not None:
            cur_rng_state = torch.cuda.get_rng_state()
            torch.cuda.set_rng_state(rng_state)
Tri Dao's avatar
Tri Dao committed
159
160
161
        dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v)
        _flash_attn_backward(
            dout, q, k, v, out, softmax_lse, dq, dk, dv, cu_seqlens_q, cu_seqlens_k,
162
163
            ctx.max_seqlen_q, ctx.max_seqlen_k, ctx.dropout_p, ctx.softmax_scale, ctx.causal,
            num_splits=1 if ctx.deterministic else 0,
Tri Dao's avatar
Tri Dao committed
164
165
166
        )
        if rng_state is not None:
            torch.cuda.set_rng_state(cur_rng_state)
167
        return dq, dk, dv, None, None, None, None, None, None, None, None, None
Tri Dao's avatar
Tri Dao committed
168
169


170
171
172
173
class FlashAttnQKVPackedSplitFunc(torch.autograd.Function):

    @staticmethod
    def forward(ctx, qkv, cu_seqlens, max_seqlen0, max_seqlen1, batch_size0, dropout_p,
174
                softmax_scale, causal, return_softmax, deterministic):
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
        # Save rng_state because the backward pass will regenerate the dropout mask
        if dropout_p > 0:
            rng_state0 = torch.cuda.get_rng_state()
            generator1 = torch.Generator(device='cuda')
            rng_state1 = generator1.get_state()
        else:
            rng_state0, generator1, rng_state1 = None, None, None
        if softmax_scale is None:
            softmax_scale = qkv.shape[-1] ** (-0.5)
        out = torch.empty_like(qkv[:, 0])
        _, softmax_lse0, S_dmask0 = _flash_attn_forward(
            qkv[:, 0], qkv[:, 1], qkv[:, 2], out, cu_seqlens[:batch_size0 + 1],
            cu_seqlens[:batch_size0 + 1], max_seqlen0, max_seqlen0, dropout_p, softmax_scale,
            causal=causal, return_softmax=return_softmax
        )
        s = torch.cuda.Stream()
        with torch.cuda.stream(s):
            _, softmax_lse1, S_dmask1 = _flash_attn_forward(
                qkv[:, 0], qkv[:, 1], qkv[:, 2], out, cu_seqlens[batch_size0:],
                cu_seqlens[batch_size0:], max_seqlen1, max_seqlen1, dropout_p, softmax_scale,
                causal=causal, return_softmax=return_softmax, generator=generator1
            )
        torch.cuda.current_stream().wait_stream(s)
        ctx.save_for_backward(qkv, out, softmax_lse0, softmax_lse1, cu_seqlens,
                              rng_state0, rng_state1)
        ctx.dropout_p = dropout_p
        ctx.max_seqlen0 = max_seqlen0
        ctx.max_seqlen1 = max_seqlen1
        ctx.batch_size0 = batch_size0
        ctx.softmax_scale = softmax_scale
        ctx.causal = causal
206
        ctx.deterministic = deterministic
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
        if not return_softmax:
            return out
        else:
            max_seqlen_q = max(softmax_lse0.shape[2], softmax_lse1.shape[2])
            max_seqlen_k = max(S_dmask0.shape[3], S_dmask1.shape[3])
            softmax_lse = torch.cat([F.pad(softmax_lse0, (0, max_seqlen_q - softmax_lse0.shape[2])),
                                     F.pad(softmax_lse1, (0, max_seqlen_q - softmax_lse1.shape[2]))],
                                    dim=0)
            return out, softmax_lse, S_dmask0, S_dmask1

    @staticmethod
    def backward(ctx, dout, *args):
        qkv, out, softmax_lse0, softmax_lse1, cu_seqlens, rng_state0, rng_state1 = ctx.saved_tensors
        batch_size0 = ctx.batch_size0
        if rng_state0 is not None:
            cur_rng_state = torch.cuda.get_rng_state()
            torch.cuda.set_rng_state(rng_state0)
        if rng_state1 is not None:
            generator1 = torch.Generator(device='cuda')
            generator1.set_state(rng_state1)
        else:
            generator1 = None
        dqkv = torch.empty_like(qkv)
        _flash_attn_backward(
            dout, qkv[:, 0], qkv[:, 1], qkv[:, 2], out, softmax_lse0,
            dqkv[:, 0], dqkv[:, 1], dqkv[:, 2], cu_seqlens[:batch_size0 + 1],
            cu_seqlens[:batch_size0 + 1], ctx.max_seqlen0, ctx.max_seqlen0, ctx.dropout_p,
234
            ctx.softmax_scale, ctx.causal, num_splits=1 if ctx.deterministic else 0,
235
236
237
238
239
240
241
        )
        s = torch.cuda.Stream()
        with torch.cuda.stream(s):
            _flash_attn_backward(
                dout, qkv[:, 0], qkv[:, 1], qkv[:, 2], out, softmax_lse1,
                dqkv[:, 0], dqkv[:, 1], dqkv[:, 2], cu_seqlens[batch_size0:],
                cu_seqlens[batch_size0:], ctx.max_seqlen1, ctx.max_seqlen1, ctx.dropout_p,
242
243
                ctx.softmax_scale, ctx.causal, generator=generator1,
                num_splits=1 if ctx.deterministic else 0,
244
245
246
247
            )
        torch.cuda.current_stream().wait_stream(s)
        if rng_state0 is not None:
            torch.cuda.set_rng_state(cur_rng_state)
248
        return dqkv, None, None, None, None, None, None, None, None, None
249
250


Tri Dao's avatar
Tri Dao committed
251
def flash_attn_unpadded_qkvpacked_func(qkv, cu_seqlens, max_seqlen, dropout_p, softmax_scale=None,
252
                                       causal=False, return_attn_probs=False, deterministic=False):
Tri Dao's avatar
Tri Dao committed
253
254
255
256
257
258
259
260
261
262
263
264
265
    """dropout_p should be set to 0.0 during evaluation
    Arguments:
        qkv: (total, 3, nheads, headdim), where total = total number of tokens in the batch.
        cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
           of the sequences in the batch, used to index into qkv.
        max_seqlen: int. Maximum sequence length in the batch.
        dropout_p: float. Dropout probability.
        softmax_scale: float. The scaling of QK^T before applying softmax.
            Default to 1 / sqrt(headdim).
        causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
        return_attn_probs: bool. Whether to return the attention probabilities. This option is for
           testing only. The returned probabilities are not guaranteed to be correct
           (they might not have the right scaling).
266
        deterministic: bool. Whether or not to ensure deterministic execution.
Tri Dao's avatar
Tri Dao committed
267
268
269
270
271
272
273
274
275
276
    Return:
        out: (total, nheads, headdim).
        softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
            logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
            normalization factor).
        S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
            The output of softmax (possibly with different scaling). It also encodes the dropout
            pattern (negative means that location was dropped, nonnegative means it was kept).
    """
    return FlashAttnQKVPackedFunc.apply(qkv, cu_seqlens, max_seqlen, dropout_p, softmax_scale,
277
                                        causal, return_attn_probs, deterministic)
Tri Dao's avatar
Tri Dao committed
278
279
280
281


def flash_attn_unpadded_kvpacked_func(q, kv, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
                                      dropout_p, softmax_scale=None, causal=False,
282
                                      return_attn_probs=False, deterministic=False):
Tri Dao's avatar
Tri Dao committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
    """dropout_p should be set to 0.0 during evaluation
    Arguments:
        q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch.
        kv: (total_k, 2, nheads, headdim), where total_k = total number of key tokens in the batch.
        cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
           of the sequences in the batch, used to index into q.
        cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
           of the sequences in the batch, used to index into kv.
        max_seqlen_q: int. Maximum query sequence length in the batch.
        max_seqlen_k: int. Maximum key sequence length in the batch.
        dropout_p: float. Dropout probability.
        softmax_scale: float. The scaling of QK^T before applying softmax.
            Default to 1 / sqrt(headdim).
        causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
        return_attn_probs: bool. Whether to return the attention probabilities. This option is for
           testing only. The returned probabilities are not guaranteed to be correct
           (they might not have the right scaling).
300
        deterministic: bool. Whether or not to ensure deterministic execution.
Tri Dao's avatar
Tri Dao committed
301
302
303
304
305
306
307
308
309
310
311
    Return:
        out: (total, nheads, headdim).
        softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
            logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
            normalization factor).
        S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
            The output of softmax (possibly with different scaling). It also encodes the dropout
            pattern (negative means that location was dropped, nonnegative means it was kept).
    """
    return FlashAttnKVPackedFunc.apply(q, kv, cu_seqlens_q, cu_seqlens_k,
                                       max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale, causal,
312
                                       return_attn_probs, deterministic)
Tri Dao's avatar
Tri Dao committed
313
314
315


def flash_attn_unpadded_func(q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
316
317
                             dropout_p, softmax_scale=None, causal=False, return_attn_probs=False,
                             deterministic=False):
Tri Dao's avatar
Tri Dao committed
318
319
320
    """dropout_p should be set to 0.0 during evaluation
    Arguments:
        q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch.
321
322
        k: (total_k, nheads, headdim), where total_k = total number of key tokens in the batch.
        v: (total_k, nheads, headdim), where total_k = total number of key tokens in the batch.
Tri Dao's avatar
Tri Dao committed
323
324
325
326
327
328
329
330
331
332
333
334
335
        cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
           of the sequences in the batch, used to index into q.
        cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
           of the sequences in the batch, used to index into kv.
        max_seqlen_q: int. Maximum query sequence length in the batch.
        max_seqlen_k: int. Maximum key sequence length in the batch.
        dropout_p: float. Dropout probability.
        softmax_scale: float. The scaling of QK^T before applying softmax.
            Default to 1 / sqrt(headdim).
        causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
        return_attn_probs: bool. Whether to return the attention probabilities. This option is for
           testing only. The returned probabilities are not guaranteed to be correct
           (they might not have the right scaling).
336
        deterministic: bool. Whether or not to ensure deterministic execution.
Tri Dao's avatar
Tri Dao committed
337
338
339
340
341
342
343
344
345
346
    Return:
        out: (total, nheads, headdim).
        softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
            logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
            normalization factor).
        S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
            The output of softmax (possibly with different scaling). It also encodes the dropout
            pattern (negative means that location was dropped, nonnegative means it was kept).
    """
    return FlashAttnFunc.apply(q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
347
                               dropout_p, softmax_scale, causal, return_attn_probs, deterministic)
Tri Dao's avatar
Tri Dao committed
348
349


350
351
def flash_attn_unpadded_qkvpacked_split_func(
        qkv, cu_seqlens, max_seqlen0, max_seqlen1, batch_size0, dropout_p, softmax_scale=None,
352
        causal=False, return_attn_probs=False, deterministic=False):
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    """
    Split attention into 2 kernels running on 2 separate streams for performance reason:
    e.g., if the batch has some sequences of length <= 128 and some > 128, it might be faster to
    have one kernel dealing with seqlen <= 128 and one kernel for seqlen > 128.

    dropout_p should be set to 0.0 during evaluation.

    Arguments:
        qkv: (total, 3, nheads, headdim), where total = total number of tokens in the batch.
        cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths
           of the sequences in the batch, used to index into qkv.
        max_seqlen0: int. Maximum sequence length in 1st part of the batch.
        max_seqlen1: int. Maximum sequence length in 2nd part of the batch.
        batch_size0: int. Number of sequences in the 1st part of the batch.
        dropout_p: float. Dropout probability.
        softmax_scale: float. The scaling of QK^T before applying softmax.
            Default to 1 / sqrt(headdim).
        causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
        return_attn_probs: bool. Whether to return the attention probabilities. This option is for
           testing only. The returned probabilities are not guaranteed to be correct
           (they might not have the right scaling).
374
        deterministic: bool. Whether or not to ensure deterministic execution.
375
376
377
378
379
380
381
382
383
384
    Return:
        out: (total, nheads, headdim).
        softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The
            logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax
            normalization factor).
        S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen).
            The output of softmax (possibly with different scaling). It also encodes the dropout
            pattern (negative means that location was dropped, nonnegative means it was kept).
    """
    return FlashAttnQKVPackedSplitFunc.apply(qkv, cu_seqlens, max_seqlen0, max_seqlen1, batch_size0,
385
386
                                             dropout_p, softmax_scale, causal, return_attn_probs,
                                             deterministic)
387
388


Tri Dao's avatar
Tri Dao committed
389
def flash_attn_func(qkv, cu_seqlens, dropout_p, max_s, softmax_scale=None, causal=False,
Tri Dao's avatar
Tri Dao committed
390
                     return_attn_probs=False):
Tri Dao's avatar
Tri Dao committed
391
392
    """For backward-compatibility only, will remove soon.
    dropout_p should be set to 0.0 during evaluation
Tri Dao's avatar
Tri Dao committed
393
    """
Tri Dao's avatar
Tri Dao committed
394
395
    return flash_attn_unpadded_qkvpacked_func(qkv, cu_seqlens, max_s, dropout_p, softmax_scale,
                                              causal, return_attn_probs)