-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
flash_attention.py
1928 lines (1720 loc) · 73.6 KB
/
flash_attention.py
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
from typing import TYPE_CHECKING, Literal, overload
import paddle
import paddle.nn.functional as F
from paddle import _C_ops, in_dynamic_mode
from paddle.base.framework import in_dynamic_or_pir_mode
from paddle.base.layer_helper import LayerHelper
from paddle.base.wrapped_decorator import signature_safe_contextmanager
g_enable_math = None
g_enable_flash = None
g_enable_mem_efficient = None
if TYPE_CHECKING:
from collections.abc import Generator
from paddle import Tensor
@signature_safe_contextmanager
def sdp_kernel(
enable_math: bool = False,
enable_flash: bool = True,
enable_mem_efficient: bool = True,
) -> Generator[None, None, None]:
r"""
With the sdp_kernel context manager, different algorithm implementations can
be selected for scaled_dot_product_attention.
"""
global g_enable_math, g_enable_flash, g_enable_mem_efficient
original_enable_math = g_enable_math
original_enable_flash = g_enable_math
original_enable_mem_efficient = g_enable_mem_efficient
g_enable_math = enable_math
g_enable_flash = enable_flash
g_enable_mem_efficient = enable_mem_efficient
try:
yield
finally:
g_enable_math = original_enable_math
g_enable_flash = original_enable_flash
g_enable_mem_efficient = original_enable_mem_efficient
# special for XPU device
def get_triangle_upper_mask(x: Tensor) -> Tensor:
mask = paddle.full_like(x, -1e4)
mask.stop_gradient = True
mask = paddle.triu(mask, diagonal=1)
mask.stop_gradient = True
return mask
@overload
def _math_attention(
query: Tensor,
key: Tensor,
value: Tensor,
dropout_rate: float = ...,
causal: bool = ...,
return_softmax: Literal[False] = ...,
training: bool = ...,
) -> tuple[Tensor, None]: ...
@overload
def _math_attention(
query: Tensor,
key: Tensor,
value: Tensor,
dropout_rate: float = ...,
causal: bool = ...,
return_softmax: Literal[True] = ...,
training: bool = ...,
) -> tuple[Tensor, Tensor]: ...
@overload
def _math_attention(
query: Tensor,
key: Tensor,
value: Tensor,
dropout_rate: float = ...,
causal: bool = ...,
return_softmax: bool = ...,
training: bool = ...,
) -> tuple[Tensor, Tensor | None]: ...
def _math_attention(
query,
key,
value,
dropout_rate=0.0,
causal=False,
return_softmax=False,
training=True,
):
r"""
This is a basic implementation of scaled dot product attention composed of
combinations of fundamental components.
"""
head_dim = query.shape[-1]
query = paddle.transpose(query, [0, 2, 1, 3])
key = paddle.transpose(key, [0, 2, 1, 3])
value = paddle.transpose(value, [0, 2, 1, 3])
product = paddle.matmul(x=query * (head_dim**-0.5), y=key, transpose_y=True)
if not causal:
weights = F.softmax(product)
else:
# special for XPU device
place = paddle.get_device()
if "xpu" in place:
# softmax_mask_fuse_upper_triangle is not supported on XPU, use plain implementation
mask = get_triangle_upper_mask(product)
product = product + mask
weights = F.softmax(product)
else:
weights = paddle.incubate.softmax_mask_fuse_upper_triangle(product)
if dropout_rate > 0.0:
weights = F.dropout(
weights, dropout_rate, training=training, mode="upscale_in_train"
)
out = paddle.matmul(weights, value)
out = paddle.transpose(out, [0, 2, 1, 3])
return out, weights if return_softmax else None
def _select_sdp_cuda(head_dim: int) -> str:
if head_dim <= 256:
return "flash_attn"
else:
return "mem_efficient"
def _select_sdp(head_dim: int) -> str:
r"""
There are currently three different implementation options available for
scaled dot product attention, and the chosen approach depends on whether it
is determined by the sdp_kernel configuration or specified through input values.
"""
place = paddle.get_device()
if "xpu" in place:
return "flash_attn"
# not use sdp_kernel
if g_enable_flash is None:
if "gpu" not in place:
return "math"
else:
return _select_sdp_cuda(head_dim)
if (
g_enable_math is False
and g_enable_flash is False
and g_enable_mem_efficient is False
):
raise AssertionError(
"No available backend for scaled_dot_product_attention was found."
)
if g_enable_math is True:
if g_enable_flash is False and g_enable_mem_efficient is False:
return "math"
if "gpu" not in place:
return "math"
if g_enable_flash is True and g_enable_mem_efficient is True:
return _select_sdp_cuda(head_dim)
if g_enable_flash is True:
return "flash_attn"
return "mem_efficient"
@overload
def flash_attention(
query: Tensor,
key: Tensor,
value: Tensor,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[False] = ...,
*,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, None]: ...
@overload
def flash_attention(
query: Tensor,
key: Tensor,
value: Tensor,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[True] = ...,
*,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor]: ...
@overload
def flash_attention(
query: Tensor,
key: Tensor,
value: Tensor,
dropout: float = ...,
causal: bool = ...,
return_softmax: bool = ...,
*,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor | None]: ...
def flash_attention(
query,
key,
value,
dropout=0.0,
causal=False,
return_softmax=False,
*,
fixed_seed_offset=None,
rng_name="",
training=True,
name=None,
):
r"""
The equation is:
.. math::
result=softmax(\frac{ Q * K^T }{\sqrt{d}}) * V
where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module.
The dimensions of the three parameters are the same.
``d`` represents the size of the last dimension of the three parameters.
Warning:
This API is only support inputs with dtype float16 and bfloat16.
Args:
query(Tensor): The query tensor in the Attention module.
4-D tensor with shape:
[batch_size, seq_len, num_heads, head_dim].
The dtype can be float61 or bfloat16.
key(Tensor): The key tensor in the Attention module.
4-D tensor with shape:
[batch_size, seq_len, num_heads, head_dim].
The dtype can be float61 or bfloat16.
value(Tensor): The value tensor in the Attention module.
4-D tensor with shape:
[batch_size, seq_len, num_heads, head_dim].
The dtype can be float61 or bfloat16.
dropout(float): The dropout ratio.
causal(bool): Whether enable causal mode.
return_softmax(bool): Whether to return softmax.
fixed_seed_offset(Tensor|None, optional): With fixed seed, offset for dropout mask.
training(bool): Whether it is in the training phase.
rng_name(str): The name to select Generator.
name(str|None, optional): The default value is None. Normally there is no need for user
to set this property. For more information, please refer to
:ref:`api_guide_Name`.
Returns:
out(Tensor): The attention tensor.
4-D tensor with shape: [batch_size, seq_len, num_heads, head_dim].
The dtype can be float16 or bfloat16.
softmax(Tensor): The softmax tensor. None if return_softmax is False.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.seed(2023)
>>> q = paddle.rand((1, 128, 2, 16))
>>> output = paddle.nn.functional.flash_attention.flash_attention(q, q, q, 0.9, False, False)
>>> print(output)
(Tensor(shape=[1, 128, 2, 16], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[[0.34992966, 0.34456208, 0.45826620, ..., 0.39883569,
0.42132431, 0.39157745],
[0.76687670, 0.65837246, 0.69117945, ..., 0.82817286,
0.76690865, 0.71485823]],
...,
[[0.71662450, 0.57275224, 0.57053083, ..., 0.48108247,
0.53336465, 0.54540104],
[0.59137970, 0.51350880, 0.50449550, ..., 0.38860250,
0.40526697, 0.60541755]]]]), None)
"""
head_dim = query.shape[3]
sdp_func_name = _select_sdp(head_dim)
if sdp_func_name == "flash_attn":
if in_dynamic_or_pir_mode():
(result_attention, result_softmax, _, _) = _C_ops.flash_attn(
query,
key,
value,
fixed_seed_offset,
None,
dropout,
causal,
return_softmax,
not training,
rng_name,
)
return result_attention, result_softmax if return_softmax else None
helper = LayerHelper('flash_attn', **locals())
dtype = helper.input_dtype(input_param_name='q')
out = helper.create_variable_for_type_inference(dtype)
softmax = helper.create_variable_for_type_inference(dtype)
softmax_lse = helper.create_variable_for_type_inference(paddle.float32)
seed_offset = helper.create_variable_for_type_inference(paddle.int64)
inputs = {
'q': query,
'k': key,
'v': value,
'fixed_seed_offset': fixed_seed_offset,
}
outputs = {
'out': out,
'softmax': softmax,
'softmax_lse': softmax_lse,
'seed_offset': seed_offset,
}
helper.append_op(
type='flash_attn',
inputs=inputs,
outputs=outputs,
attrs={
'dropout': dropout,
'causal': causal,
'return_softmax': return_softmax,
'is_test': not training,
'rng_name': rng_name,
},
)
return out, softmax if return_softmax else None
else:
if sdp_func_name == "mem_efficient":
from paddle.incubate.nn.memory_efficient_attention import (
memory_efficient_attention,
)
output = memory_efficient_attention(
query,
key,
value,
attn_bias=None,
p=dropout,
scale=None,
training=training,
)
return output, None
else:
return _math_attention(
query,
key,
value,
dropout_rate=dropout,
causal=causal,
return_softmax=return_softmax,
training=training,
)
@overload
def flash_attn_qkvpacked(
qkv: Tensor,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[False] = ...,
*,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, None]: ...
@overload
def flash_attn_qkvpacked(
qkv: Tensor,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[True] = ...,
*,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor]: ...
@overload
def flash_attn_qkvpacked(
qkv: Tensor,
dropout: float = ...,
causal: bool = ...,
return_softmax: bool = ...,
*,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor | None]: ...
def flash_attn_qkvpacked(
qkv,
dropout=0.0,
causal=False,
return_softmax=False,
*,
fixed_seed_offset=None,
rng_name="",
training=True,
name=None,
):
r"""
The equation is:
.. math::
result=softmax(\frac{ Q * K^T }{\sqrt{d}}) * V
where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module.
The dimensions of the three parameters are the same.
``d`` represents the size of the last dimension of the three parameters.
Warning:
This API only supports inputs with dtype float16 and bfloat16.
Don't call this API if flash_attn is not supported.
Args:
qkv(Tensor): The query/key/value packed tensor in the Attention module.
5-D tensor with shape:
[batchsize, seqlen , num_heads/num_heads_k + 2, num_heads_k, head_dim].
The dtype can be float16 or bfloat16.
dropout(float): The dropout ratio.
causal(bool): Whether enable causal mode.
return_softmax(bool): Whether to return softmax.
fixed_seed_offset(Tensor|None, optional): With fixed seed, offset for dropout mask.
training(bool): Whether it is in the training phase.
rng_name(str): The name to select Generator.
name(str|None, optional): The default value is None. Normally there is no need for user
to set this property. For more information, please refer to
:ref:`api_guide_Name`.
Returns:
- out(Tensor). The attention tensor. 4-D tensor with shape: [batch_size, seq_len, num_heads, head_dim]. The dtype can be float16 or bfloat16.
- softmax(Tensor). The softmax tensor. None if return_softmax is False.
Examples:
.. code-block:: python
>>> # doctest: +SKIP('flash_attn need A100 compile')
>>> import paddle
>>> paddle.seed(2023)
>>> q = paddle.rand((1, 128, 2, 16))
>>> qkv = paddle.stack([q, q, q], axis=2)
>>> output = paddle.nn.functional.flash_attn_qkvpacked(qkv, 0.9, False, False)
>>> print(output)
(Tensor(shape=[1, 128, 2, 16], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[[0.34992966, 0.34456208, 0.45826620, ..., 0.39883569,
0.42132431, 0.39157745],
[0.76687670, 0.65837246, 0.69117945, ..., 0.82817286,
0.76690865, 0.71485823]],
...,
[[0.71662450, 0.57275224, 0.57053083, ..., 0.48108247,
0.53336465, 0.54540104],
[0.59137970, 0.51350880, 0.50449550, ..., 0.38860250,
0.40526697, 0.60541755]]]]), None)
>>> # doctest: -SKIP
"""
head_dim = qkv.shape[-1]
sdp_func_name = _select_sdp(head_dim)
if sdp_func_name == "flash_attn":
if in_dynamic_or_pir_mode():
(
result_attention,
result_softmax,
_,
_,
) = _C_ops.flash_attn_qkvpacked(
qkv,
fixed_seed_offset,
None,
dropout,
causal,
return_softmax,
not training,
rng_name,
)
return result_attention, result_softmax if return_softmax else None
helper = LayerHelper('flash_attn_qkvpacked', **locals())
dtype = helper.input_dtype(input_param_name='qkv')
out = helper.create_variable_for_type_inference(dtype)
softmax = helper.create_variable_for_type_inference(dtype)
softmax_lse = helper.create_variable_for_type_inference(paddle.float32)
seed_offset = helper.create_variable_for_type_inference(paddle.int64)
inputs = {
'qkv': qkv,
'fixed_seed_offset': fixed_seed_offset,
}
outputs = {
'out': out,
'softmax': softmax,
'softmax_lse': softmax_lse,
'seed_offset': seed_offset,
}
helper.append_op(
type='flash_attn_qkvpacked',
inputs=inputs,
outputs=outputs,
attrs={
'dropout': dropout,
'causal': causal,
'return_softmax': return_softmax,
'is_test': not training,
'rng_name': rng_name,
},
)
return out, softmax if return_softmax else None
else:
# don't call qkvpacked if not using flash_attn
query = qkv[:, :, :-2].reshape([0, 0, -1, qkv.shape[-1]])
key = qkv[:, :, -2]
value = qkv[:, :, -1]
if sdp_func_name == "mem_efficient":
from paddle.incubate.nn.memory_efficient_attention import (
memory_efficient_attention,
)
output = memory_efficient_attention(
query,
key,
value,
attn_bias=None,
p=dropout,
scale=None,
training=training,
)
return output, None
else:
return _math_attention(
query,
key,
value,
dropout_rate=dropout,
causal=causal,
return_softmax=return_softmax,
training=training,
)
@overload
def flash_attn_unpadded(
query: Tensor,
key: Tensor,
value: Tensor,
cu_seqlens_q: Tensor,
cu_seqlens_k: Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
scale: float,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[False] = ...,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, None]: ...
@overload
def flash_attn_unpadded(
query: Tensor,
key: Tensor,
value: Tensor,
cu_seqlens_q: Tensor,
cu_seqlens_k: Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
scale: float,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[True] = ...,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor]: ...
@overload
def flash_attn_unpadded(
query: Tensor,
key: Tensor,
value: Tensor,
cu_seqlens_q: Tensor,
cu_seqlens_k: Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
scale: float,
dropout: float = ...,
causal: bool = ...,
return_softmax: bool = ...,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor | None]: ...
def flash_attn_unpadded(
query,
key,
value,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
scale,
dropout=0.0,
causal=False,
return_softmax=False,
fixed_seed_offset=None,
rng_name='',
training=True,
name=None,
):
r"""
The equation is:
.. math::
result=softmax(\frac{ Q * K^T }{\sqrt{d}}) * V
where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module.
The dimensions of the three parameters are the same.
``d`` represents the size of the last dimension of the three parameters.
Warning:
This API is only support inputs with dtype float16 and bfloat16.
Args:
query(Tensor): The query tensor in the Attention module.
3-D tensor with shape:
[total_seq_len, num_heads, head_dim].
The dtype can be float61 or bfloat16.
key(Tensor): The key tensor in the Attention module.
3-D tensor with shape:
[total_seq_len, num_heads, head_dim].
The dtype can be float61 or bfloat16.
value(Tensor): The value tensor in the Attention module.
3-D tensor with shape:
[total_seq_len, num_heads, head_dim].
The dtype can be float61 or bfloat16.
cu_seqlens_q(Tensor): The cumulative sequence lengths of the sequences in the batch,
used to index query.
cu_seqlens_k(Tensor): The cumulative sequence lengths of the sequences in the batch,
used to index key and value.
max_seqlen_q(int): Maximum sequence length of query in the batch.
max_seqlen_k(int): Maximum sequence length of key/value in the batch.
scale(float): The scaling of QK^T before applying softmax.
dropout(float, optional): The dropout ratio.
causal(bool, optional): Whether enable causal mode.
return_softmax(bool, optional): Whether to return softmax.
fixed_seed_offset(Tensor|None, optional): With fixed seed, offset for dropout mask.
rng_name(str, optional): The name to select Generator.
training(bool, optional): Whether it is in the training phase.
name(str|None, optional): The default value is None. Normally there is no need for user
to set this property. For more information, please refer to
:ref:`api_guide_Name`.
Returns:
out(Tensor): The attention tensor.
3-D tensor with shape: [total_seq_len, num_heads, head_dim].
The dtype can be float16 or bfloat16.
softmax(Tensor): The softmax tensor. None if return_softmax is False.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.seed(2023)
>>> q = paddle.rand((2, 128, 8, 16), dtype='float16')
>>> cu = paddle.arange(0, 384, 128, dtype='int32')
>>> qq = paddle.reshape(q, [256, 8, 16])
>>> output = paddle.nn.functional.flash_attention.flash_attn_unpadded(qq, qq, qq, cu, cu, 128, 128, 0.25, 0.0, False, False)
"""
if in_dynamic_mode():
(
result_attention,
result_softmax,
) = _C_ops.flash_attn_unpadded(
query,
key,
value,
cu_seqlens_q,
cu_seqlens_k,
fixed_seed_offset,
None,
max_seqlen_q,
max_seqlen_k,
scale,
dropout,
causal,
return_softmax,
not training,
rng_name,
)
return result_attention, result_softmax if return_softmax else None
helper = LayerHelper('flash_attn_unpadded', **locals())
dtype = helper.input_dtype(input_param_name='q')
out = helper.create_variable_for_type_inference(dtype)
softmax = helper.create_variable_for_type_inference(dtype)
softmax_lse = helper.create_variable_for_type_inference(paddle.float32)
seed_offset = helper.create_variable_for_type_inference(paddle.int64)
inputs = {
'q': query,
'k': key,
'v': value,
'cu_seqlens_q': cu_seqlens_q,
'cu_seqlens_k': cu_seqlens_k,
'fixed_seed_offset': fixed_seed_offset,
}
outputs = {
'out': out,
'softmax': softmax,
'softmax_lse': softmax_lse,
'seed_offset': seed_offset,
}
helper.append_op(
type='flash_attn_unpadded',
inputs=inputs,
outputs=outputs,
attrs={
'max_seqlen_q': max_seqlen_q,
'max_seqlen_k': max_seqlen_k,
'scale': scale,
'dropout': dropout,
'causal': causal,
'return_softmax': return_softmax,
'is_test': not training,
'rng_name': rng_name,
},
)
return out, softmax if return_softmax else None
@overload
def flash_attn_varlen_qkvpacked(
qkv: Tensor,
cu_seqlens_q: Tensor,
cu_seqlens_k: Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
scale: float,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[False] = ...,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
varlen_padded: bool = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, None]: ...
@overload
def flash_attn_varlen_qkvpacked(
qkv: Tensor,
cu_seqlens_q: Tensor,
cu_seqlens_k: Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
scale: float,
dropout: float = ...,
causal: bool = ...,
return_softmax: Literal[True] = ...,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
varlen_padded: bool = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor]: ...
@overload
def flash_attn_varlen_qkvpacked(
qkv: Tensor,
cu_seqlens_q: Tensor,
cu_seqlens_k: Tensor,
max_seqlen_q: int,
max_seqlen_k: int,
scale: float,
dropout: float = ...,
causal: bool = ...,
return_softmax: bool = ...,
fixed_seed_offset: Tensor | None = ...,
rng_name: str = ...,
varlen_padded: bool = ...,
training: bool = ...,
name: str | None = ...,
) -> tuple[Tensor, Tensor | None]: ...
def flash_attn_varlen_qkvpacked(
qkv,
cu_seqlens_q,
cu_seqlens_k,
max_seqlen_q,
max_seqlen_k,
scale,
dropout=0.0,
causal=False,
return_softmax=False,
fixed_seed_offset=None,
rng_name="",
varlen_padded=True,
training=True,
name=None,
):
r"""
The equation is:
.. math::
result=softmax(\frac{ Q * K^T }{\sqrt{d}}) * V
where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module.
The dimensions of the three parameters are the same.
``d`` represents the size of the last dimension of the three parameters.
Warning:
This API only supports inputs with dtype float16 and bfloat16.
Args:
qkv(Tensor): The padded query/key/value packed tensor in the Attention module. The padding part won't be computed
4-D tensor with shape:
[total_seq_len, num_heads/num_heads_k + 2, num_heads_k, head_dim].
The dtype can be float16 or bfloat16.
cu_seqlens_q(Tensor): The cumulative sequence lengths of the sequences in the batch,
used to index query.
cu_seqlens_k(Tensor): The cumulative sequence lengths of the sequences in the batch,
used to index key and value.
max_seqlen_q(int): Maximum sequence length of query in the batch. Note it's the padding length, not the max actual seqlen
max_seqlen_k(int): Maximum sequence length of key/value in the batch.
scale(float): The scaling of QK^T before applying softmax.
dropout(float, optional): The dropout ratio.
causal(bool, optional): Whether enable causal mode.
return_softmax(bool, optional): Whether to return softmax.
fixed_seed_offset(Tensor|None, optional): With fixed seed, offset for dropout mask.
rng_name(str, optional): The name to select Generator.
training(bool, optional): Whether it is in the training phase.
name(str|None, optional): The default value is None. Normally there is no need for user
to set this property. For more information, please refer to
:ref:`api_guide_Name`.
Returns:
- out(Tensor). The attention tensor. The tensor is padded by zeros. 3-D tensor with shape: [total_seq_len, num_heads, head_dim]. The dtype can be float16 or bfloat16.
- softmax(Tensor). The softmax tensor. None if return_softmax is False.
Examples:
.. code-block:: python
>>> # doctest: +SKIP('flash_attn need A100 compile')
>>> import paddle
>>> paddle.seed(2023)
>>> q = paddle.rand((2, 128, 8, 16), dtype='float16')
>>> cu = paddle.arange(0, 384, 128, dtype='int32')
>>> qq = paddle.reshape(q, [256, 8, 16])
>>> qkv = paddle.stack([qq, qq, qq], axis=2)
>>> output = paddle.nn.functional.flash_attn_varlen_qkvpacked(qkv, cu, cu, 128, 128, 0.25, 0.0, False, False)
>>> # doctest: -SKIP
"""
if in_dynamic_mode():
(
result_attention,
result_softmax,
) = _C_ops.flash_attn_varlen_qkvpacked(
qkv,
cu_seqlens_q,
cu_seqlens_k,
fixed_seed_offset,
None,
max_seqlen_q,
max_seqlen_k,
scale,
dropout,
causal,
return_softmax,
not training,
rng_name,
varlen_padded,
)
return result_attention, result_softmax if return_softmax else None
helper = LayerHelper('flash_attn_varlen_qkvpacked', **locals())
dtype = helper.input_dtype(input_param_name='qkv')
out = helper.create_variable_for_type_inference(dtype)
softmax = helper.create_variable_for_type_inference(dtype)
softmax_lse = helper.create_variable_for_type_inference(paddle.float32)
seed_offset = helper.create_variable_for_type_inference(paddle.int64)
inputs = {
'qkv': qkv,
'cu_seqlens_q': cu_seqlens_q,
'cu_seqlens_k': cu_seqlens_k,
'fixed_seed_offset': fixed_seed_offset,
}
outputs = {
'out': out,
'softmax': softmax,
'softmax_lse': softmax_lse,
'seed_offset': seed_offset,
}
helper.append_op(
type='flash_attn_varlen_qkvpacked',
inputs=inputs,
outputs=outputs,
attrs={
'max_seqlen_q': max_seqlen_q,
'max_seqlen_k': max_seqlen_k,
'scale': scale,
'dropout': dropout,
'causal': causal,
'return_softmax': return_softmax,
'is_test': not training,
'rng_name': rng_name,
},
)
return out, softmax if return_softmax else None
def scaled_dot_product_attention(
query: Tensor,
key: Tensor,
value: Tensor,
attn_mask: Tensor | None = None,
dropout_p: float = 0.0,
is_causal: bool = False,
training: bool = True,
name: str | None = None,
) -> Tensor:
r"""
The equation is:
.. math::
result=softmax(\frac{ Q * K^T }{\sqrt{d}}) * V
where : ``Q``, ``K``, and ``V`` represent the three input parameters of the attention module.
The dimensions of the three parameters are the same.
``d`` represents the size of the last dimension of the three parameters.
Warning:
This API only supports inputs with dtype float16 and bfloat16.
Args: