Jackmin108 commited on
Commit
4fa2261
1 Parent(s): 96e9a75

Delete flash_attn_triton.py

Browse files
Files changed (1) hide show
  1. flash_attn_triton.py +0 -1172
flash_attn_triton.py DELETED
@@ -1,1172 +0,0 @@
1
- # Copyright (c) 2022, Tri Dao.
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
- *Experimental* implementation of FlashAttention in Triton.
16
- Tested with triton==2.0.0.dev20221202.
17
- Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
18
- other than 64:
19
- https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
20
- We'll update this implementation with the new Triton backend once this is fixed.
21
-
22
- We use the FlashAttention implementation from Phil Tillet a starting point.
23
- https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
24
-
25
- Changes:
26
- - Implement both causal and non-causal attention.
27
- - Implement both self-attention and cross-attention.
28
- - Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
29
- - Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
30
- - Support attention bias.
31
- - Speed up the forward pass a bit, and only store the LSE instead of m and l.
32
- - Make the backward for d=128 much faster by reducing register spilling.
33
- - Optionally parallelize the backward pass across seqlen_k, to deal with the case of
34
- small batch size * nheads.
35
-
36
- Caution:
37
- - This is an *experimental* implementation. The forward pass should be quite robust but
38
- I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
39
- - This implementation has only been tested on A100.
40
- - If you plan to use headdim other than 64 and 128, you should test for race conditions
41
- (due to the Triton compiler), as done in tests/test_flash_attn.py
42
- "test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
43
- for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
44
- that there are none left for other head dimensions.
45
-
46
- Differences between this Triton version and the CUDA version:
47
- - Triton version doesn't support dropout.
48
- - Triton forward is generally faster than CUDA forward, while Triton backward is
49
- generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
50
- than CUDA forward + backward.
51
- - Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
52
- - Triton version supports attention bias, while CUDA version doesn't.
53
- """
54
-
55
- import math
56
-
57
- import torch
58
- import triton
59
- import triton.language as tl
60
-
61
-
62
- # Disabling autotune for now, set num_warps=4 if headdim=64 and num_warps=8 if headdim=128
63
- # @triton.autotune(
64
- # configs=[
65
- # triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1),
66
- # # This config has a race condition when EVEN_M == False, disabling it for now.
67
- # # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1),
68
- # ],
69
- # key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM']
70
- # )
71
- @triton.heuristics(
72
- {
73
- "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
74
- "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
75
- "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
76
- }
77
- )
78
- @triton.jit
79
- def _fwd_kernel(
80
- Q,
81
- K,
82
- V,
83
- Bias,
84
- Out,
85
- Lse,
86
- TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug
87
- softmax_scale,
88
- stride_qb,
89
- stride_qh,
90
- stride_qm,
91
- stride_kb,
92
- stride_kh,
93
- stride_kn,
94
- stride_vb,
95
- stride_vh,
96
- stride_vn,
97
- stride_bb,
98
- stride_bh,
99
- stride_bm,
100
- stride_ob,
101
- stride_oh,
102
- stride_om,
103
- nheads,
104
- seqlen_q,
105
- seqlen_k,
106
- seqlen_q_rounded,
107
- headdim,
108
- CACHE_KEY_SEQLEN_Q,
109
- CACHE_KEY_SEQLEN_K,
110
- BIAS_TYPE: tl.constexpr,
111
- IS_CAUSAL: tl.constexpr,
112
- BLOCK_HEADDIM: tl.constexpr,
113
- EVEN_M: tl.constexpr,
114
- EVEN_N: tl.constexpr,
115
- EVEN_HEADDIM: tl.constexpr,
116
- BLOCK_M: tl.constexpr,
117
- BLOCK_N: tl.constexpr,
118
- ):
119
- start_m = tl.program_id(0)
120
- off_hb = tl.program_id(1)
121
- off_b = off_hb // nheads
122
- off_h = off_hb % nheads
123
- # off_b = tl.program_id(1)
124
- # off_h = tl.program_id(2)
125
- # off_hb = off_b * nheads + off_h
126
- # initialize offsets
127
- offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
128
- offs_n = tl.arange(0, BLOCK_N)
129
- offs_d = tl.arange(0, BLOCK_HEADDIM)
130
- # Initialize pointers to Q, K, V
131
- # Adding parenthesis around indexing might use int32 math instead of int64 math?
132
- # https://github.com/openai/triton/issues/741
133
- # I'm seeing a tiny bit of difference (5-7us)
134
- q_ptrs = (
135
- Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
136
- )
137
- k_ptrs = (
138
- K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
139
- )
140
- v_ptrs = (
141
- V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
142
- )
143
- if BIAS_TYPE == "vector":
144
- b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
145
- elif BIAS_TYPE == "matrix":
146
- b_ptrs = (
147
- Bias
148
- + off_b * stride_bb
149
- + off_h * stride_bh
150
- + (offs_m[:, None] * stride_bm + offs_n[None, :])
151
- )
152
- # initialize pointer to m and l
153
- t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
154
- lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
155
- m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
156
- acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
157
- # load q: it will stay in SRAM throughout
158
- # [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call
159
- # tl.load(q_ptrs), we get the wrong output!
160
- if EVEN_M & EVEN_N:
161
- if EVEN_HEADDIM:
162
- q = tl.load(q_ptrs)
163
- else:
164
- q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
165
- else:
166
- if EVEN_HEADDIM:
167
- q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
168
- else:
169
- q = tl.load(
170
- q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0
171
- )
172
- # loop over k, v and update accumulator
173
- end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
174
- for start_n in range(0, end_n, BLOCK_N):
175
- start_n = tl.multiple_of(start_n, BLOCK_N)
176
- # -- compute qk ----
177
- if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
178
- if EVEN_HEADDIM:
179
- k = tl.load(k_ptrs + start_n * stride_kn)
180
- else:
181
- k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
182
- else:
183
- if EVEN_HEADDIM:
184
- k = tl.load(
185
- k_ptrs + start_n * stride_kn,
186
- mask=(start_n + offs_n)[:, None] < seqlen_k,
187
- other=0.0,
188
- )
189
- else:
190
- k = tl.load(
191
- k_ptrs + start_n * stride_kn,
192
- mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
193
- other=0.0,
194
- )
195
- qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
196
- qk += tl.dot(q, k, trans_b=True)
197
- # Trying to combine the two masks seem to make the result wrong
198
- if not EVEN_N: # Need to mask out otherwise the softmax is wrong
199
- qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float("-inf"))
200
- if IS_CAUSAL:
201
- qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float("-inf"))
202
- if BIAS_TYPE != "none":
203
- if BIAS_TYPE == "vector":
204
- if EVEN_N:
205
- bias = tl.load(b_ptrs + start_n).to(tl.float32)
206
- else:
207
- bias = tl.load(
208
- b_ptrs + start_n, mask=(start_n + offs_n) < seqlen_k, other=0.0
209
- ).to(tl.float32)
210
- bias = bias[None, :]
211
- elif BIAS_TYPE == "matrix":
212
- if EVEN_M & EVEN_N:
213
- bias = tl.load(b_ptrs + start_n).to(tl.float32)
214
- else:
215
- bias = tl.load(
216
- b_ptrs + start_n,
217
- mask=(offs_m[:, None] < seqlen_q)
218
- & ((start_n + offs_n)[None, :] < seqlen_k),
219
- other=0.0,
220
- ).to(tl.float32)
221
- # Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler
222
- # can then fuse the mult and add into an fma instruction. But if we have bias we need to
223
- # to multiply with softmax_scale here.
224
- qk = qk * softmax_scale + bias
225
- m_ij = tl.maximum(tl.max(qk, 1), lse_i)
226
- p = tl.exp(qk - m_ij[:, None])
227
- else:
228
- m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
229
- p = tl.exp(qk * softmax_scale - m_ij[:, None])
230
- l_ij = tl.sum(p, 1)
231
-
232
- # scale acc_o
233
- acc_o_scale = tl.exp(m_i - m_ij)
234
-
235
- # # -- update output accumulator --
236
- # BUG: have to store and immediately load
237
- tl.store(t_ptrs, acc_o_scale)
238
- acc_o_scale = tl.load(t_ptrs)
239
- acc_o = acc_o * acc_o_scale[:, None]
240
- # update acc_o
241
- if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition
242
- if EVEN_HEADDIM:
243
- v = tl.load(v_ptrs + start_n * stride_vn)
244
- else:
245
- v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
246
- else:
247
- if EVEN_HEADDIM:
248
- v = tl.load(
249
- v_ptrs + start_n * stride_vn,
250
- mask=(start_n + offs_n)[:, None] < seqlen_k,
251
- other=0.0,
252
- )
253
- else:
254
- v = tl.load(
255
- v_ptrs + start_n * stride_vn,
256
- mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim),
257
- other=0.0,
258
- )
259
- p = p.to(v.dtype)
260
- acc_o += tl.dot(p, v)
261
-
262
- # -- update statistics
263
- m_i = m_ij
264
- l_i_new = tl.exp(lse_i - m_ij) + l_ij
265
- lse_i = m_ij + tl.log(l_i_new)
266
-
267
- o_scale = tl.exp(m_i - lse_i)
268
- # BUG: have to store and immediately load
269
- tl.store(t_ptrs, o_scale)
270
- o_scale = tl.load(t_ptrs)
271
- acc_o = acc_o * o_scale[:, None]
272
- # rematerialize offsets to save registers
273
- start_m = tl.program_id(0)
274
- offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
275
- # write back l and m
276
- lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
277
- tl.store(lse_ptrs, lse_i)
278
- # initialize pointers to output
279
- offs_d = tl.arange(0, BLOCK_HEADDIM)
280
- out_ptrs = (
281
- Out
282
- + off_b * stride_ob
283
- + off_h * stride_oh
284
- + (offs_m[:, None] * stride_om + offs_d[None, :])
285
- )
286
- if EVEN_M:
287
- if EVEN_HEADDIM:
288
- tl.store(out_ptrs, acc_o)
289
- else:
290
- tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
291
- else:
292
- if EVEN_HEADDIM:
293
- tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
294
- else:
295
- tl.store(
296
- out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim)
297
- )
298
-
299
-
300
- @triton.jit
301
- def _bwd_preprocess_do_o_dot(
302
- Out,
303
- DO,
304
- Delta,
305
- stride_ob,
306
- stride_oh,
307
- stride_om,
308
- stride_dob,
309
- stride_doh,
310
- stride_dom,
311
- nheads,
312
- seqlen_q,
313
- seqlen_q_rounded,
314
- headdim,
315
- BLOCK_M: tl.constexpr,
316
- BLOCK_HEADDIM: tl.constexpr,
317
- ):
318
- start_m = tl.program_id(0)
319
- off_hb = tl.program_id(1)
320
- off_b = off_hb // nheads
321
- off_h = off_hb % nheads
322
- # initialize offsets
323
- offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
324
- offs_d = tl.arange(0, BLOCK_HEADDIM)
325
- # load
326
- o = tl.load(
327
- Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :],
328
- mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
329
- other=0.0,
330
- ).to(tl.float32)
331
- do = tl.load(
332
- DO
333
- + off_b * stride_dob
334
- + off_h * stride_doh
335
- + offs_m[:, None] * stride_dom
336
- + offs_d[None, :],
337
- mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
338
- other=0.0,
339
- ).to(tl.float32)
340
- delta = tl.sum(o * do, axis=1)
341
- # write-back
342
- tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
343
-
344
-
345
- @triton.jit
346
- def _bwd_store_dk_dv(
347
- dk_ptrs,
348
- dv_ptrs,
349
- dk,
350
- dv,
351
- offs_n,
352
- offs_d,
353
- seqlen_k,
354
- headdim,
355
- EVEN_M: tl.constexpr,
356
- EVEN_N: tl.constexpr,
357
- EVEN_HEADDIM: tl.constexpr,
358
- ):
359
- # [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False,
360
- # if we just call tl.store(dv_ptrs), there's a race condition
361
- if EVEN_N & EVEN_M:
362
- if EVEN_HEADDIM:
363
- tl.store(dv_ptrs, dv)
364
- tl.store(dk_ptrs, dk)
365
- else:
366
- tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
367
- tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
368
- else:
369
- if EVEN_HEADDIM:
370
- tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
371
- tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
372
- else:
373
- tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
374
- tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
375
-
376
-
377
- @triton.jit
378
- def _bwd_kernel_one_col_block(
379
- start_n,
380
- Q,
381
- K,
382
- V,
383
- Bias,
384
- DO,
385
- DQ,
386
- DK,
387
- DV,
388
- LSE,
389
- D,
390
- softmax_scale,
391
- stride_qm,
392
- stride_kn,
393
- stride_vn,
394
- stride_bm,
395
- stride_dom,
396
- stride_dqm,
397
- stride_dkn,
398
- stride_dvn,
399
- seqlen_q,
400
- seqlen_k,
401
- headdim,
402
- ATOMIC_ADD: tl.constexpr,
403
- BIAS_TYPE: tl.constexpr,
404
- IS_CAUSAL: tl.constexpr,
405
- BLOCK_HEADDIM: tl.constexpr,
406
- EVEN_M: tl.constexpr,
407
- EVEN_N: tl.constexpr,
408
- EVEN_HEADDIM: tl.constexpr,
409
- BLOCK_M: tl.constexpr,
410
- BLOCK_N: tl.constexpr,
411
- ):
412
- # We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N)
413
- begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M
414
- # initialize row/col offsets
415
- offs_qm = begin_m + tl.arange(0, BLOCK_M)
416
- offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
417
- offs_m = tl.arange(0, BLOCK_M)
418
- offs_d = tl.arange(0, BLOCK_HEADDIM)
419
- # initialize pointers to value-like data
420
- q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
421
- k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
422
- v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
423
- do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
424
- dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
425
- if BIAS_TYPE == "vector":
426
- b_ptrs = Bias + offs_n
427
- elif BIAS_TYPE == "matrix":
428
- b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
429
- # initialize dv and dk
430
- dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
431
- dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
432
- # There seems to be some problem with Triton pipelining that makes results wrong for
433
- # headdim=64, seqlen=(113, 255), bias_type='matrix'. In this case the for loop
434
- # may have zero step, and pipelining with the bias matrix could screw it up.
435
- # So we just exit early.
436
- if begin_m >= seqlen_q:
437
- dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
438
- dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
439
- _bwd_store_dk_dv(
440
- dk_ptrs,
441
- dv_ptrs,
442
- dk,
443
- dv,
444
- offs_n,
445
- offs_d,
446
- seqlen_k,
447
- headdim,
448
- EVEN_M=EVEN_M,
449
- EVEN_N=EVEN_N,
450
- EVEN_HEADDIM=EVEN_HEADDIM,
451
- )
452
- return
453
- # k and v stay in SRAM throughout
454
- # [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False,
455
- # if we just call tl.load(k_ptrs), we get the wrong output!
456
- if EVEN_N & EVEN_M:
457
- if EVEN_HEADDIM:
458
- k = tl.load(k_ptrs)
459
- v = tl.load(v_ptrs)
460
- else:
461
- k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
462
- v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
463
- else:
464
- if EVEN_HEADDIM:
465
- k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
466
- v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
467
- else:
468
- k = tl.load(
469
- k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0
470
- )
471
- v = tl.load(
472
- v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0
473
- )
474
- # loop over rows
475
- num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
476
- for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
477
- start_m = tl.multiple_of(start_m, BLOCK_M)
478
- offs_m_curr = start_m + offs_m
479
- # load q, k, v, do on-chip
480
- # Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117)
481
- if EVEN_M & EVEN_HEADDIM:
482
- q = tl.load(q_ptrs)
483
- else:
484
- if EVEN_HEADDIM:
485
- q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
486
- else:
487
- q = tl.load(
488
- q_ptrs,
489
- mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
490
- other=0.0,
491
- )
492
- # recompute p = softmax(qk, dim=-1).T
493
- qk = tl.dot(q, k, trans_b=True)
494
- # Trying to combine the two masks seem to make the result wrong
495
- if not EVEN_N: # Need to mask out otherwise the softmax is wrong
496
- qk = tl.where(offs_n[None, :] < seqlen_k, qk, float("-inf"))
497
- if IS_CAUSAL:
498
- qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf"))
499
- if BIAS_TYPE != "none":
500
- tl.debug_barrier() # Race condition otherwise
501
- if BIAS_TYPE == "vector":
502
- if EVEN_N:
503
- bias = tl.load(b_ptrs).to(tl.float32)
504
- else:
505
- bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
506
- bias = bias[None, :]
507
- elif BIAS_TYPE == "matrix":
508
- if EVEN_M & EVEN_N:
509
- bias = tl.load(b_ptrs).to(tl.float32)
510
- else:
511
- bias = tl.load(
512
- b_ptrs,
513
- mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k),
514
- other=0.0,
515
- ).to(tl.float32)
516
- qk = qk * softmax_scale + bias
517
- # There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong.
518
- # Also wrong for headdim=64.
519
- if not (EVEN_M & EVEN_HEADDIM):
520
- tl.debug_barrier()
521
- lse_i = tl.load(LSE + offs_m_curr)
522
- if BIAS_TYPE == "none":
523
- p = tl.exp(qk * softmax_scale - lse_i[:, None])
524
- else:
525
- p = tl.exp(qk - lse_i[:, None])
526
- # compute dv
527
- # [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call
528
- # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs
529
- # in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512,
530
- # the output is correct.
531
- if EVEN_M & EVEN_HEADDIM:
532
- do = tl.load(do_ptrs)
533
- else:
534
- # [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask.
535
- do = tl.load(
536
- do_ptrs,
537
- mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
538
- other=0.0,
539
- )
540
- # if EVEN_M:
541
- # if EVEN_HEADDIM:
542
- # do = tl.load(do_ptrs)
543
- # else:
544
- # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
545
- # else:
546
- # if EVEN_HEADDIM:
547
- # do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
548
- # else:
549
- # do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q)
550
- # & (offs_d[None, :] < headdim), other=0.0)
551
- dv += tl.dot(p.to(do.dtype), do, trans_a=True)
552
- # compute dp = dot(v, do)
553
- # There seems to be a race condition when headdim=48/96, and dq, dk are wrong.
554
- # Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True
555
- # Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False
556
- if not (EVEN_M & EVEN_HEADDIM):
557
- tl.debug_barrier()
558
- dp = tl.dot(do, v, trans_b=True)
559
- # There's a race condition for headdim=48
560
- if not EVEN_HEADDIM:
561
- tl.debug_barrier()
562
- # compute ds = p * (dp - delta[:, None])
563
- # Putting the subtraction after the dp matmul (instead of before) is slightly faster
564
- Di = tl.load(D + offs_m_curr)
565
- # Converting ds to q.dtype here reduces register pressure and makes it much faster
566
- # for BLOCK_HEADDIM=128
567
- ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
568
- # compute dk = dot(ds.T, q)
569
- dk += tl.dot(ds, q, trans_a=True)
570
- # compute dq
571
- if not (
572
- EVEN_M & EVEN_HEADDIM
573
- ): # Otherewise there's a race condition when BIAS_TYPE='matrix'
574
- tl.debug_barrier()
575
- if not ATOMIC_ADD:
576
- if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
577
- dq = tl.load(dq_ptrs, eviction_policy="evict_last")
578
- dq += tl.dot(ds, k)
579
- tl.store(dq_ptrs, dq, eviction_policy="evict_last")
580
- else:
581
- if EVEN_HEADDIM:
582
- dq = tl.load(
583
- dq_ptrs,
584
- mask=offs_m_curr[:, None] < seqlen_q,
585
- other=0.0,
586
- eviction_policy="evict_last",
587
- )
588
- dq += tl.dot(ds, k)
589
- tl.store(
590
- dq_ptrs,
591
- dq,
592
- mask=offs_m_curr[:, None] < seqlen_q,
593
- eviction_policy="evict_last",
594
- )
595
- else:
596
- dq = tl.load(
597
- dq_ptrs,
598
- mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
599
- other=0.0,
600
- eviction_policy="evict_last",
601
- )
602
- dq += tl.dot(ds, k)
603
- tl.store(
604
- dq_ptrs,
605
- dq,
606
- mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
607
- eviction_policy="evict_last",
608
- )
609
- else: # If we're parallelizing across the seqlen_k dimension
610
- dq = tl.dot(ds, k)
611
- if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M
612
- tl.atomic_add(dq_ptrs, dq)
613
- else:
614
- if EVEN_HEADDIM:
615
- tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
616
- else:
617
- tl.atomic_add(
618
- dq_ptrs,
619
- dq,
620
- mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim),
621
- )
622
- # increment pointers
623
- dq_ptrs += BLOCK_M * stride_dqm
624
- q_ptrs += BLOCK_M * stride_qm
625
- do_ptrs += BLOCK_M * stride_dom
626
- if BIAS_TYPE == "matrix":
627
- b_ptrs += BLOCK_M * stride_bm
628
- # write-back
629
- dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
630
- dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
631
- _bwd_store_dk_dv(
632
- dk_ptrs,
633
- dv_ptrs,
634
- dk,
635
- dv,
636
- offs_n,
637
- offs_d,
638
- seqlen_k,
639
- headdim,
640
- EVEN_M=EVEN_M,
641
- EVEN_N=EVEN_N,
642
- EVEN_HEADDIM=EVEN_HEADDIM,
643
- )
644
-
645
-
646
- def init_to_zero(name):
647
- return lambda nargs: nargs[name].zero_()
648
-
649
-
650
- @triton.autotune(
651
- configs=[
652
- triton.Config(
653
- {"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": False},
654
- num_warps=8,
655
- num_stages=1,
656
- pre_hook=init_to_zero("DQ"),
657
- ),
658
- triton.Config(
659
- {"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": True},
660
- num_warps=8,
661
- num_stages=1,
662
- pre_hook=init_to_zero("DQ"),
663
- ),
664
- # Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now
665
- # # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4*
666
- # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
667
- # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')),
668
- # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
669
- # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')),
670
- ],
671
- key=["CACHE_KEY_SEQLEN_Q", "CACHE_KEY_SEQLEN_K", "BIAS_TYPE", "IS_CAUSAL", "BLOCK_HEADDIM"],
672
- )
673
- @triton.heuristics(
674
- {
675
- "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0,
676
- "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0,
677
- "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"],
678
- }
679
- )
680
- @triton.jit
681
- def _bwd_kernel(
682
- Q,
683
- K,
684
- V,
685
- Bias,
686
- DO,
687
- DQ,
688
- DK,
689
- DV,
690
- LSE,
691
- D,
692
- softmax_scale,
693
- stride_qb,
694
- stride_qh,
695
- stride_qm,
696
- stride_kb,
697
- stride_kh,
698
- stride_kn,
699
- stride_vb,
700
- stride_vh,
701
- stride_vn,
702
- stride_bb,
703
- stride_bh,
704
- stride_bm,
705
- stride_dob,
706
- stride_doh,
707
- stride_dom,
708
- stride_dqb,
709
- stride_dqh,
710
- stride_dqm,
711
- stride_dkb,
712
- stride_dkh,
713
- stride_dkn,
714
- stride_dvb,
715
- stride_dvh,
716
- stride_dvn,
717
- nheads,
718
- seqlen_q,
719
- seqlen_k,
720
- seqlen_q_rounded,
721
- headdim,
722
- CACHE_KEY_SEQLEN_Q,
723
- CACHE_KEY_SEQLEN_K,
724
- BIAS_TYPE: tl.constexpr,
725
- IS_CAUSAL: tl.constexpr,
726
- BLOCK_HEADDIM: tl.constexpr,
727
- SEQUENCE_PARALLEL: tl.constexpr,
728
- EVEN_M: tl.constexpr,
729
- EVEN_N: tl.constexpr,
730
- EVEN_HEADDIM: tl.constexpr,
731
- BLOCK_M: tl.constexpr,
732
- BLOCK_N: tl.constexpr,
733
- ):
734
- off_hb = tl.program_id(1)
735
- off_b = off_hb // nheads
736
- off_h = off_hb % nheads
737
- # offset pointers for batch/head
738
- Q += off_b * stride_qb + off_h * stride_qh
739
- K += off_b * stride_kb + off_h * stride_kh
740
- V += off_b * stride_vb + off_h * stride_vh
741
- DO += off_b * stride_dob + off_h * stride_doh
742
- DQ += off_b * stride_dqb + off_h * stride_dqh
743
- DK += off_b * stride_dkb + off_h * stride_dkh
744
- DV += off_b * stride_dvb + off_h * stride_dvh
745
- if BIAS_TYPE != "none":
746
- Bias += off_b * stride_bb + off_h * stride_bh
747
- # pointer to row-wise quantities in value-like data
748
- D += off_hb * seqlen_q_rounded
749
- LSE += off_hb * seqlen_q_rounded
750
- if not SEQUENCE_PARALLEL:
751
- num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
752
- for start_n in range(0, num_block_n):
753
- _bwd_kernel_one_col_block(
754
- start_n,
755
- Q,
756
- K,
757
- V,
758
- Bias,
759
- DO,
760
- DQ,
761
- DK,
762
- DV,
763
- LSE,
764
- D,
765
- softmax_scale,
766
- stride_qm,
767
- stride_kn,
768
- stride_vn,
769
- stride_bm,
770
- stride_dom,
771
- stride_dqm,
772
- stride_dkn,
773
- stride_dvn,
774
- seqlen_q,
775
- seqlen_k,
776
- headdim,
777
- ATOMIC_ADD=False,
778
- BIAS_TYPE=BIAS_TYPE,
779
- IS_CAUSAL=IS_CAUSAL,
780
- BLOCK_HEADDIM=BLOCK_HEADDIM,
781
- EVEN_M=EVEN_M,
782
- EVEN_N=EVEN_N,
783
- EVEN_HEADDIM=EVEN_HEADDIM,
784
- BLOCK_M=BLOCK_M,
785
- BLOCK_N=BLOCK_N,
786
- )
787
- else:
788
- start_n = tl.program_id(0)
789
- _bwd_kernel_one_col_block(
790
- start_n,
791
- Q,
792
- K,
793
- V,
794
- Bias,
795
- DO,
796
- DQ,
797
- DK,
798
- DV,
799
- LSE,
800
- D,
801
- softmax_scale,
802
- stride_qm,
803
- stride_kn,
804
- stride_vn,
805
- stride_bm,
806
- stride_dom,
807
- stride_dqm,
808
- stride_dkn,
809
- stride_dvn,
810
- seqlen_q,
811
- seqlen_k,
812
- headdim,
813
- ATOMIC_ADD=True,
814
- BIAS_TYPE=BIAS_TYPE,
815
- IS_CAUSAL=IS_CAUSAL,
816
- BLOCK_HEADDIM=BLOCK_HEADDIM,
817
- EVEN_M=EVEN_M,
818
- EVEN_N=EVEN_N,
819
- EVEN_HEADDIM=EVEN_HEADDIM,
820
- BLOCK_M=BLOCK_M,
821
- BLOCK_N=BLOCK_N,
822
- )
823
-
824
-
825
- def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
826
- # shape constraints
827
- batch, seqlen_q, nheads, d = q.shape
828
- _, seqlen_k, _, _ = k.shape
829
- assert k.shape == (batch, seqlen_k, nheads, d)
830
- assert v.shape == (batch, seqlen_k, nheads, d)
831
- assert d <= 128, "FlashAttention only support head dimensions up to 128"
832
- assert q.dtype == k.dtype == v.dtype, "All tensors must have the same type"
833
- assert q.dtype in [torch.float16, torch.bfloat16], "Only support fp16 and bf16"
834
- assert q.is_cuda and k.is_cuda and v.is_cuda
835
- softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
836
-
837
- has_bias = bias is not None
838
- bias_type = "none"
839
- if has_bias:
840
- assert bias.dtype in [q.dtype, torch.float]
841
- assert bias.is_cuda
842
- assert bias.dim() == 4
843
- if bias.stride(-1) != 1:
844
- bias = bias.contiguous()
845
- if bias.shape[2:] == (1, seqlen_k):
846
- bias_type = "vector"
847
- elif bias.shape[2:] == (seqlen_q, seqlen_k):
848
- bias_type = "matrix"
849
- else:
850
- raise RuntimeError(
851
- "Last 2 dimensions of bias must be (1, seqlen_k)" " or (seqlen_q, seqlen_k)"
852
- )
853
- bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
854
- bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
855
-
856
- seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
857
- lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
858
- tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
859
- o = torch.empty_like(q)
860
-
861
- BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
862
- BLOCK = 128
863
- num_warps = 4 if d <= 64 else 8
864
- grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads)
865
- _fwd_kernel[grid](
866
- q,
867
- k,
868
- v,
869
- bias,
870
- o,
871
- lse,
872
- tmp,
873
- softmax_scale,
874
- q.stride(0),
875
- q.stride(2),
876
- q.stride(1),
877
- k.stride(0),
878
- k.stride(2),
879
- k.stride(1),
880
- v.stride(0),
881
- v.stride(2),
882
- v.stride(1),
883
- *bias_strides,
884
- o.stride(0),
885
- o.stride(2),
886
- o.stride(1),
887
- nheads,
888
- seqlen_q,
889
- seqlen_k,
890
- seqlen_q_rounded,
891
- d,
892
- seqlen_q // 32,
893
- seqlen_k // 32, # key for triton cache (limit number of compilations)
894
- # Can't use kwargs here because triton autotune expects key to be args, not kwargs
895
- # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
896
- bias_type,
897
- causal,
898
- BLOCK_HEADDIM,
899
- BLOCK_M=BLOCK,
900
- BLOCK_N=BLOCK,
901
- num_warps=num_warps,
902
- num_stages=1,
903
- )
904
- return o, lse, softmax_scale # softmax_scale could have been updated
905
-
906
-
907
- def _flash_attn_backward(
908
- do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None
909
- ):
910
- # Make sure that the last dimension is contiguous
911
- if do.stride(-1) != 1:
912
- do = do.contiguous()
913
- batch, seqlen_q, nheads, d = q.shape
914
- _, seqlen_k, _, _ = k.shape
915
- # assert d in {16, 32, 64, 128}
916
- assert d <= 128
917
- seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
918
- assert lse.shape == (batch, nheads, seqlen_q_rounded)
919
- assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
920
- assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
921
- softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
922
- # dq_accum = torch.zeros_like(q, dtype=torch.float32)
923
- dq_accum = torch.empty_like(q, dtype=torch.float32)
924
- delta = torch.empty_like(lse)
925
- # delta = torch.zeros_like(lse)
926
-
927
- BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
928
- grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads)
929
- _bwd_preprocess_do_o_dot[grid](
930
- o,
931
- do,
932
- delta,
933
- o.stride(0),
934
- o.stride(2),
935
- o.stride(1),
936
- do.stride(0),
937
- do.stride(2),
938
- do.stride(1),
939
- nheads,
940
- seqlen_q,
941
- seqlen_q_rounded,
942
- d,
943
- BLOCK_M=128,
944
- BLOCK_HEADDIM=BLOCK_HEADDIM,
945
- )
946
-
947
- has_bias = bias is not None
948
- bias_type = "none"
949
- if has_bias:
950
- assert bias.dtype in [q.dtype, torch.float]
951
- assert bias.is_cuda
952
- assert bias.dim() == 4
953
- assert bias.stride(-1) == 1
954
- if bias.shape[2:] == (1, seqlen_k):
955
- bias_type = "vector"
956
- elif bias.shape[2:] == (seqlen_q, seqlen_k):
957
- bias_type = "matrix"
958
- else:
959
- raise RuntimeError(
960
- "Last 2 dimensions of bias must be (1, seqlen_k)" " or (seqlen_q, seqlen_k)"
961
- )
962
- bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
963
- bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
964
-
965
- # BLOCK_M = 128
966
- # BLOCK_N = 64
967
- # num_warps = 4
968
- grid = lambda META: (
969
- triton.cdiv(seqlen_k, META["BLOCK_N"]) if META["SEQUENCE_PARALLEL"] else 1,
970
- batch * nheads,
971
- )
972
- _bwd_kernel[grid](
973
- q,
974
- k,
975
- v,
976
- bias,
977
- do,
978
- dq_accum,
979
- dk,
980
- dv,
981
- lse,
982
- delta,
983
- softmax_scale,
984
- q.stride(0),
985
- q.stride(2),
986
- q.stride(1),
987
- k.stride(0),
988
- k.stride(2),
989
- k.stride(1),
990
- v.stride(0),
991
- v.stride(2),
992
- v.stride(1),
993
- *bias_strides,
994
- do.stride(0),
995
- do.stride(2),
996
- do.stride(1),
997
- dq_accum.stride(0),
998
- dq_accum.stride(2),
999
- dq_accum.stride(1),
1000
- dk.stride(0),
1001
- dk.stride(2),
1002
- dk.stride(1),
1003
- dv.stride(0),
1004
- dv.stride(2),
1005
- dv.stride(1),
1006
- nheads,
1007
- seqlen_q,
1008
- seqlen_k,
1009
- seqlen_q_rounded,
1010
- d,
1011
- seqlen_q // 32,
1012
- seqlen_k // 32, # key for triton cache (limit number of compilations)
1013
- # Can't use kwargs here because triton autotune expects key to be args, not kwargs
1014
- # IS_CAUSAL=causal, BLOCK_HEADDIM=d,
1015
- bias_type,
1016
- causal,
1017
- BLOCK_HEADDIM,
1018
- # SEQUENCE_PARALLEL=False,
1019
- # BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N,
1020
- # num_warps=num_warps,
1021
- # num_stages=1,
1022
- )
1023
- dq.copy_(dq_accum)
1024
-
1025
-
1026
- class FlashAttnQKVPackedFunc(torch.autograd.Function):
1027
- @staticmethod
1028
- def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
1029
- """
1030
- qkv: (batch, seqlen, 3, nheads, headdim)
1031
- bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
1032
- For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
1033
- ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
1034
- """
1035
- # Make sure that the last dimension is contiguous
1036
- if qkv.stride(-1) != 1:
1037
- qkv = qkv.contiguous()
1038
- o, lse, ctx.softmax_scale = _flash_attn_forward(
1039
- qkv[:, :, 0],
1040
- qkv[:, :, 1],
1041
- qkv[:, :, 2],
1042
- bias=bias,
1043
- causal=causal,
1044
- softmax_scale=softmax_scale,
1045
- )
1046
- ctx.save_for_backward(qkv, o, lse, bias)
1047
- ctx.causal = causal
1048
- return o
1049
-
1050
- @staticmethod
1051
- def backward(ctx, do):
1052
- qkv, o, lse, bias = ctx.saved_tensors
1053
- assert not ctx.needs_input_grad[1], "FlashAttention does not support bias gradient yet"
1054
- # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1055
- # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1056
- with torch.inference_mode():
1057
- dqkv = torch.empty_like(qkv)
1058
- _flash_attn_backward(
1059
- do,
1060
- qkv[:, :, 0],
1061
- qkv[:, :, 1],
1062
- qkv[:, :, 2],
1063
- o,
1064
- lse,
1065
- dqkv[:, :, 0],
1066
- dqkv[:, :, 1],
1067
- dqkv[:, :, 2],
1068
- bias=bias,
1069
- causal=ctx.causal,
1070
- softmax_scale=ctx.softmax_scale,
1071
- )
1072
- return dqkv, None, None, None
1073
-
1074
-
1075
- flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
1076
-
1077
-
1078
- class FlashAttnKVPackedFunc(torch.autograd.Function):
1079
- @staticmethod
1080
- def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
1081
- """
1082
- q: (batch, seqlen_q, nheads, headdim)
1083
- kv: (batch, seqlen_k, 2, nheads, headdim)
1084
- bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
1085
- For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
1086
- ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
1087
- """
1088
- # Make sure that the last dimension is contiguous
1089
- q, kv = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
1090
- o, lse, ctx.softmax_scale = _flash_attn_forward(
1091
- q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale
1092
- )
1093
- ctx.save_for_backward(q, kv, o, lse, bias)
1094
- ctx.causal = causal
1095
- return o
1096
-
1097
- @staticmethod
1098
- def backward(ctx, do):
1099
- q, kv, o, lse, bias = ctx.saved_tensors
1100
- if len(ctx.needs_input_grad) >= 3:
1101
- assert not ctx.needs_input_grad[2], "FlashAttention does not support bias gradient yet"
1102
- # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1103
- # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1104
- with torch.inference_mode():
1105
- dq = torch.empty_like(q)
1106
- dkv = torch.empty_like(kv)
1107
- _flash_attn_backward(
1108
- do,
1109
- q,
1110
- kv[:, :, 0],
1111
- kv[:, :, 1],
1112
- o,
1113
- lse,
1114
- dq,
1115
- dkv[:, :, 0],
1116
- dkv[:, :, 1],
1117
- bias=bias,
1118
- causal=ctx.causal,
1119
- softmax_scale=ctx.softmax_scale,
1120
- )
1121
- return dq, dkv, None, None, None
1122
-
1123
-
1124
- flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
1125
-
1126
-
1127
- class FlashAttnFunc(torch.autograd.Function):
1128
- @staticmethod
1129
- def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
1130
- """
1131
- q: (batch_size, seqlen_q, nheads, headdim)
1132
- k, v: (batch_size, seqlen_k, nheads, headdim)
1133
- bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
1134
- For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
1135
- ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
1136
- """
1137
- # Make sure that the last dimension is contiguous
1138
- q, k, v = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
1139
- o, lse, ctx.softmax_scale = _flash_attn_forward(
1140
- q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale
1141
- )
1142
- ctx.save_for_backward(q, k, v, o, lse, bias)
1143
- ctx.causal = causal
1144
- return o
1145
-
1146
- @staticmethod
1147
- def backward(ctx, do):
1148
- q, k, v, o, lse, bias = ctx.saved_tensors
1149
- assert not ctx.needs_input_grad[3], "FlashAttention does not support bias gradient yet"
1150
- # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd
1151
- # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version.
1152
- with torch.inference_mode():
1153
- dq = torch.empty_like(q)
1154
- dk = torch.empty_like(k)
1155
- dv = torch.empty_like(v)
1156
- _flash_attn_backward(
1157
- do,
1158
- q,
1159
- k,
1160
- v,
1161
- o,
1162
- lse,
1163
- dq,
1164
- dk,
1165
- dv,
1166
- bias=bias,
1167
- causal=ctx.causal,
1168
- softmax_scale=ctx.softmax_scale,
1169
- )
1170
- return dq, dk, dv, None, None, None
1171
-
1172
- flash_attn_func = FlashAttnFunc.apply