-
Notifications
You must be signed in to change notification settings - Fork 264
/
Copy pathattention.cpp
2789 lines (2578 loc) · 94.1 KB
/
attention.cpp
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
#include <ATen/ATen.h>
#include <ATen/TensorSubclassLikeUtils.h>
#include <ATen/cpp_custom_type_hack.h>
#include <ATen/native/DispatchStub.h>
#include <ATen/native/nested/NestedTensorUtils.h>
#include <ATen/native/transformers/attention.h>
#include <ATen/record_function.h>
#include <ATen/xpu/XPUGeneratorImpl.h>
#include <CL/sycl.hpp>
#include <runtime/Device.h>
#include <runtime/Utils.h>
#include <torch/autograd.h>
#include <torch/custom_class.h>
#include <utils/DPCPP.h>
#include <cstdint>
#include "../Blas.h"
#include "../DistributionTemplates.h"
#include "../RandomEngine.h"
#include "../comm/ATDispatch.h"
#include "../comm/AccumulateType.h"
#include "dropout.h"
#include "sdp_utils.h"
#include "utils/CustomOperatorRegistration.h"
using namespace torch::autograd;
namespace at {
namespace AtenIpexTypeXPU {
bool is_fmha_supported_tensor(const Tensor& input, bool seq_last = false) {
// Normal tensors are in BNFH format
// In addition, BFNH format tensor is also supported
// If seq_last is true, the tensor could be in FBNH format
if (input.is_contiguous() || input.transpose(1, 2).is_contiguous() ||
(seq_last && input.permute({2, 0, 1, 3}).is_contiguous())) {
return true;
}
return false;
}
std::tuple<Tensor, Tensor, Tensor, Tensor> ipex_sdp_dropout_backward(
const Tensor& grad_out,
const Tensor& query,
const Tensor& key,
const Tensor& value,
const c10::optional<Tensor>& attn_bias,
const Tensor& out,
const Tensor& logsumexp,
const Tensor& dropout_mask,
double dropout_p,
bool grad_input_mask,
bool causal,
c10::optional<double> scale);
inline Tensor _scaled_dot_product_efficient_attention_impl(
const Tensor& query,
const Tensor& key,
const Tensor& value,
const c10::optional<Tensor>& attn_mask,
const c10::optional<at::Tensor>& dropout_mask,
const c10::optional<at::Tensor>& seed_t,
const c10::optional<at::Tensor>& offset_t,
Tensor& softmax_lse,
bool is_causal,
bool is_training,
double dropout_p,
c10::optional<double> scale) {
#if defined(USE_XETLA)
// check attn_mask padded
uint32_t attn_mask_padded_block_size = 0;
if (attn_mask.has_value()) {
std::vector<int64_t> sz = attn_mask->sizes().vec();
int64_t lastDim = sz[sz.size() - 1];
int64_t alignTo = 8;
attn_mask_padded_block_size = alignTo * ((lastDim + alignTo - 1) / alignTo);
}
Tensor query_in;
Tensor key_in;
Tensor value_in;
if (!is_fmha_supported_tensor(query)) {
query_in = query.contiguous();
} else
query_in = query;
if (!is_fmha_supported_tensor(key)) {
key_in = key.contiguous();
} else
key_in = key;
if (!is_fmha_supported_tensor(value)) {
value_in = value.contiguous();
} else
value_in = value;
// create strided output
// size [bs, num_head, qsize, head_size]
// layout [bs, qsize, num_head, head_size]
auto output = at::empty_like(query_in);
auto dpcpp_queue = dpcppGetCurrentQueue();
const double softmax_scale =
scale.has_value() ? scale.value() : (1.0 / std::sqrt(query_in.size(-1)));
const bool use_dropout = std::fpclassify(dropout_p) != FP_ZERO;
auto xeType = sdp::aten_to_Xetla_dtype(query_in);
gpu::xetla::gpu_arch xeArch = gpu::xetla::get_xetla_current_arch_tag();
auto cgfs = gpu::xetla::fmha_forward_kernel(
xeArch,
xeType,
{query_in.data_ptr(),
key_in.data_ptr(),
value_in.data_ptr(),
/* alibi */ nullptr,
attn_mask.has_value() ? attn_mask->data_ptr() : (void*)nullptr,
dropout_mask.has_value() ? dropout_mask->data_ptr() : (void*)nullptr,
output.data_ptr(),
softmax_lse.data_ptr(),
softmax_scale,
/* beta */ 1.0f,
dropout_p,
nullptr,
nullptr,
query_in.size(0),
query_in.size(1),
key_in.size(1),
query_in.size(3),
query_in.size(2),
key_in.size(2),
query_in.stride(0),
query_in.stride(1),
query_in.stride(2),
key_in.stride(0),
key_in.stride(1),
key_in.stride(2),
attn_mask.has_value() ? attn_mask->stride(0) : -1,
attn_mask.has_value() ? attn_mask->stride(1) : -1,
attn_mask.has_value() ? attn_mask->stride(2) : -1,
/* ablibi padded size */ 0,
attn_mask_padded_block_size,
is_causal,
false,
is_training,
use_dropout,
false, // use varlen
seed_t.has_value() ? (uint64_t)*seed_t.value().data_ptr<int64_t>() : -1,
offset_t.has_value() ? (uint64_t)*offset_t.value().data_ptr<int64_t>()
: -1});
DPCPP_Q_SUBMIT_CGFS(dpcpp_queue, cgfs);
return output;
#else
AT_ERROR("SDP: xetla library not found in compilation");
// TODO: sycl kernel impl for efficient_attention
// auto result = naive_scaled_dot_product(query, key, value, is_causal);
// return std::forward_as_tuple(std::get<0>(result), std::get<1>(result));
#endif
}
std::tuple<at::Tensor, at::Tensor> pre_process_group_query_attention_input(
const at::Tensor& query,
const at::Tensor& key,
const at::Tensor& value,
const bool enable_gqa) {
if (!enable_gqa) {
return std::make_tuple(key, value);
}
const auto q_num_heads = query.sym_size(-3);
const auto k_num_heads = key.sym_size(-3);
const auto v_num_heads = value.sym_size(-3);
bool all_equal = q_num_heads == k_num_heads && k_num_heads == v_num_heads;
bool key_divisible = q_num_heads % k_num_heads == 0;
bool value_divisible = q_num_heads % v_num_heads == 0;
TORCH_CHECK(
all_equal || (key_divisible && value_divisible),
"Number of heads in key and value must divide the number of heads in ");
if (all_equal) {
return std::make_tuple(key, value);
}
auto repeat_key_shape = query.sym_size(-3) / key.sym_size(-3);
auto repeat_value_shape = query.sym_size(-3) / value.sym_size(-3);
at::Tensor key_repeated = key.repeat_interleave_symint(repeat_key_shape, -3);
at::Tensor value_repeated =
value.repeat_interleave_symint(repeat_value_shape, -3);
return std::make_tuple(std::move(key_repeated), std::move(value_repeated));
}
std::tuple<Tensor, Tensor> _scaled_dot_product_attention_math_native_impl(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const std::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
const std::optional<Tensor>& dropout_mask,
std::optional<double> scale,
bool enable_gqa) {
if (query_.is_nested() || key.is_nested() || value.is_nested()) {
TORCH_CHECK(
query_.is_contiguous() && key.is_contiguous() && value.is_contiguous(),
"scaled_dot_product_attention: If inputs are nested tensors they must be contiguous");
}
auto attn_mask = attn_mask_;
// Naive, composite implementation defined here.
// Scale q, k before matmul for stability see https://tinyurl.com/sudb9s96 for
// math
bool is_negative_scaling = scale.has_value() && scale.value() < 0.0;
const auto scaling_factor =
sdp::native_calculate_scale(
query_, is_negative_scaling ? std::abs(scale.value()) : scale)
.sqrt();
const auto query = query_ *
(is_negative_scaling ? c10::SymFloat(0.0) - scaling_factor
: scaling_factor);
if (is_causal) {
TORCH_CHECK(
!attn_mask.has_value(),
"_scaled_dot_product_attention: Explicit attn_mask should not be set when is_causal=True");
TORCH_CHECK(
!query.is_nested() && !key.is_nested(),
"_scaled_dot_product_attention: Nested tensors for query / key are not supported when is_causal=True");
// Replace attn_mask with causal mask; lower triangular elements take part
// in attention.
const auto L = query.sym_size(-2), S = key.sym_size(-2);
attn_mask =
at::ones_symint({L, S}, query.options().dtype(at::kBool)).tril();
attn_mask = sdp::convert_boolean_attn_mask(attn_mask, query.dtype());
}
// MQA/GQA handling
auto [key_expanded, value_expanded] =
pre_process_group_query_attention_input(query, key, value, enable_gqa);
auto attn =
at::matmul(query, key_expanded.transpose(-2, -1) * scaling_factor);
if (attn_mask.has_value()) {
if (at::areAnyTensorSubclassLike({attn, *attn_mask})) {
attn = attn.add(*attn_mask);
} else {
attn.add_(*attn_mask);
}
}
attn = at::softmax(attn, -1);
if (dropout_p > 0.0) {
if (dropout_mask.has_value()) {
// In order to validate the correctness of the fused kernels, we need to
// use the same dropout mask in order to compare the results.
TORCH_WARN_ONCE("Dropout mask should only be used for testing purposes.");
attn = attn.masked_fill(dropout_mask->logical_not(), 0.0);
auto dropout_scaling = 1.0 / (1 - dropout_p);
return std::make_tuple(
at::matmul(attn, value_expanded * dropout_scaling), attn);
} else {
attn = at::dropout(attn, dropout_p, true);
}
}
return std::make_tuple(at::matmul(attn, value_expanded), attn);
}
std::tuple<Tensor, Tensor> _scaled_dot_product_attention_math_impl(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const std::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
const std::optional<Tensor>& dropout_mask,
std::optional<double> scale,
bool enable_gqa) {
if (query_.is_nested() || key.is_nested() || value.is_nested()) {
TORCH_CHECK(
query_.is_contiguous() && key.is_contiguous() && value.is_contiguous(),
"scaled_dot_product_attention: If inputs are nested tensors they must be contiguous");
}
auto attn_mask = attn_mask_;
// Naive, composite implementation defined here.
// [Original] Scale q, k before matmul for stability see
// https://tinyurl.com/sudb9s96 for math
// Here we apply scaling after matmul for op fusion purpose
bool is_negative_scaling = scale.has_value() && scale.value() < 0.0;
const auto orig_scaling_factor = sdp::calculate_scale(
query_, is_negative_scaling ? std::abs(scale.value()) : scale);
if (is_causal) {
TORCH_CHECK(
!attn_mask.has_value(),
"_scaled_dot_product_attention: Explicit attn_mask should not be set when is_causal=True");
TORCH_CHECK(
!query_.is_nested() && !key.is_nested(),
"_scaled_dot_product_attention: Nested tensors for query / key are not supported when is_causal=True");
// Replace attn_mask with causal mask; lower triangular elements take part
// in attention.
const auto L = query_.sym_size(-2), S = key.sym_size(-2);
attn_mask =
at::ones_symint({L, S}, query_.options().dtype(at::kBool)).tril();
attn_mask = sdp::convert_boolean_attn_mask(attn_mask, query_.dtype());
}
// MQA/GQA handling
auto [key_expanded, value_expanded] =
pre_process_group_query_attention_input(query_, key, value, enable_gqa);
Tensor attn;
if (attn_mask.has_value()) {
attn_mask = attn_mask->contiguous();
if (is_negative_scaling) {
attn = trans_matmul_div_add(
key_expanded,
/*dim1=*/-1,
/*dim2=*/-1,
query_,
c10::SymFloat(0.0) - orig_scaling_factor,
*attn_mask,
1.0);
} else {
attn = trans_matmul_div_add(
key_expanded,
/*dim1=*/-1,
/*dim2=*/-1,
query_,
orig_scaling_factor,
*attn_mask,
1.0);
}
} else {
if (is_negative_scaling) {
attn = trans_matmul_div_scalar(
key_expanded,
/*dim1=*/-1,
/*dim2=*/-1,
query_,
c10::SymFloat(0.0) - orig_scaling_factor);
} else {
attn = trans_matmul_div_scalar(
key_expanded, /*dim1=*/-1, /*dim2=*/-1, query_, orig_scaling_factor);
}
}
attn = at::softmax(attn, -1);
if (dropout_p > 0.0) {
if (dropout_mask.has_value()) {
// In order to validate the correctness of the fused kernels, we need to
// use the same dropout mask in order to compare the results.
TORCH_WARN_ONCE("Dropout mask should only be used for testing purposes.");
attn = attn.masked_fill(dropout_mask->logical_not(), 0.0);
auto dropout_scaling = 1.0 / (1 - dropout_p);
return std::make_tuple(
at::matmul(attn, value_expanded * dropout_scaling), attn);
} else {
attn = at::dropout(attn, dropout_p, true);
}
}
return std::make_tuple(at::matmul(attn, value_expanded), attn);
}
std::tuple<Tensor, Tensor> _scaled_dot_product_attention_math(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const std::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
const std::optional<Tensor>& dropout_mask,
std::optional<double> scale,
bool enable_gqa) {
// on ATSM, the efficient_attention path is not available
// With naive math path, oneDNN matmul has overflow issue with fp16 inputs
// as a WA, convert fp16 inputs to fp32
if (query_.requires_grad() || key.requires_grad() || value.requires_grad()) {
return IPEX_DISPATCH_FLOATING_TYPES_AND2(
at::kHalf,
at::kBFloat16,
query_.scalar_type(),
"scaled_dot_product_attention_math",
[&] {
bool is_half = std::is_same<scalar_t, at::Half>::value;
if (is_half) {
std::optional<Tensor> attn_mask_fp32;
Tensor query_fp32 = query_.to(at::kFloat);
Tensor key_fp32 = key.to(at::kFloat);
Tensor value_fp32 = value.to(at::kFloat);
if (attn_mask_.has_value()) {
attn_mask_fp32 = attn_mask_.value().to(at::kFloat);
} else {
attn_mask_fp32 = attn_mask_;
}
auto [attn_output, attn_weight] =
_scaled_dot_product_attention_math_native_impl(
query_fp32,
key_fp32,
value_fp32,
attn_mask_fp32,
dropout_p,
is_causal,
dropout_mask,
scale,
enable_gqa);
return std::make_tuple(
attn_output.to(at::kHalf), attn_weight.to(at::kHalf));
}
return _scaled_dot_product_attention_math_native_impl(
query_,
key,
value,
attn_mask_,
dropout_p,
is_causal,
dropout_mask,
scale,
enable_gqa);
});
} else {
// accelerate for inference
return IPEX_DISPATCH_FLOATING_TYPES_AND2(
at::kHalf,
at::kBFloat16,
query_.scalar_type(),
"scaled_dot_product_attention_math",
[&] {
bool is_half = std::is_same<scalar_t, at::Half>::value;
if (is_half) {
std::optional<Tensor> attn_mask_fp32;
Tensor query_fp32 = query_.to(at::kFloat);
Tensor key_fp32 = key.to(at::kFloat);
Tensor value_fp32 = value.to(at::kFloat);
if (attn_mask_.has_value()) {
attn_mask_fp32 = attn_mask_.value().to(at::kFloat);
} else {
attn_mask_fp32 = attn_mask_;
}
auto [attn_output, attn_weight] =
_scaled_dot_product_attention_math_impl(
query_fp32,
key_fp32,
value_fp32,
attn_mask_fp32,
dropout_p,
is_causal,
dropout_mask,
scale,
enable_gqa);
return std::make_tuple(
attn_output.to(at::kHalf), attn_weight.to(at::kHalf));
}
return _scaled_dot_product_attention_math_impl(
query_,
key,
value,
attn_mask_,
dropout_p,
is_causal,
dropout_mask,
scale,
enable_gqa);
});
}
}
std::tuple<Tensor, Tensor, Tensor, Tensor>
_scaled_dot_product_efficient_attention(
const Tensor& query,
const Tensor& key,
const Tensor& value,
const c10::optional<at::Tensor>& attn_bias,
bool compute_log_sumexp,
double dropout_p,
bool is_causal,
c10::optional<double> scale) {
int64_t B = query.size(0);
int64_t num_heads = query.size(1);
int64_t M = query.size(-2);
int64_t N = key.size(-2);
auto gen = get_generator_or_default<at::XPUGeneratorImpl>(
c10::nullopt, at::xpu::detail::getDefaultXPUGenerator());
std::pair<uint64_t, uint64_t> philox_state;
{
// See Note [Acquire lock when using random generators]
std::lock_guard<std::mutex> lock(gen->mutex_);
philox_state = gen->philox_engine_inputs(B * num_heads * M * N);
}
PhiloxState rng_engine_inputs(
std::get<0>(philox_state), std::get<1>(philox_state));
auto [seed, offset] = philox_unpack(rng_engine_inputs);
Tensor seed_t = at::scalar_tensor(
at::Scalar(static_cast<int64_t>(seed)), at::dtype(at::kLong));
Tensor offset_t = at::scalar_tensor(
at::Scalar(static_cast<int64_t>(offset)), at::dtype(at::kLong));
auto softmax_lse = at::empty(
{query.size(0), query.size(1), query.size(2)},
query.options().dtype(at::kFloat));
auto out = _scaled_dot_product_efficient_attention_impl(
query,
key,
value,
attn_bias,
c10::nullopt,
seed_t,
offset_t,
softmax_lse,
is_causal,
compute_log_sumexp,
dropout_p,
scale);
return std::make_tuple(
std::move(out),
std::move(softmax_lse),
std::move(seed_t),
std::move(offset_t));
}
std::tuple<Tensor, Tensor, Tensor> ipex_sdp_dropout_forward(
const Tensor& query,
const Tensor& key,
const Tensor& value,
const c10::optional<at::Tensor>& attn_bias,
bool compute_log_sumexp,
double dropout_p,
bool is_causal,
c10::optional<double> scale) {
RECORD_FUNCTION("ipex_sdp_dropout_forward", {});
int64_t B = query.size(0);
int64_t num_heads = query.size(1);
int64_t M = query.size(-2);
int64_t N = key.size(-2);
const bool use_dropout = std::fpclassify(dropout_p) != FP_ZERO;
Tensor dropout_mask = at::empty(
{B, num_heads, M, N},
query.options().dtype(c10::CppTypeToScalarType<uint8_t>::value));
if (use_dropout) {
dropout_mask = at::AtenIpexTypeXPU::dropout_mask_only<uint8_t>(
dropout_mask, dropout_p);
}
auto softmax_lse = at::empty(
{query.size(0), query.size(1), query.size(2)},
query.options().dtype(at::kFloat));
auto out = _scaled_dot_product_efficient_attention_impl(
query,
key,
value,
attn_bias,
dropout_mask,
c10::nullopt,
c10::nullopt,
softmax_lse,
is_causal,
compute_log_sumexp,
dropout_p,
scale);
return std::make_tuple(
std::move(out), std::move(softmax_lse), std::move(dropout_mask));
}
class IPEXSDPDropoutOp : public Function<IPEXSDPDropoutOp> {
public:
static variable_list forward(
AutogradContext* ctx,
const Tensor& query,
const Tensor& key,
const Tensor& value,
const c10::optional<at::Tensor>& attn_bias,
bool compute_log_sumexp,
double dropout_p,
bool is_causal,
c10::optional<double> scale) {
ctx->saved_data["dropout_p"] = dropout_p;
ctx->saved_data["is_causal"] = is_causal;
ctx->saved_data["scale"] = scale;
ctx->saved_data["attn_bias"] = attn_bias;
ctx->saved_data["attn_bias_requires_grad"] =
attn_bias.has_value() ? attn_bias.value().requires_grad() : false;
auto outputs = ipex_sdp_dropout_forward(
query,
key,
value,
attn_bias,
compute_log_sumexp,
dropout_p,
is_causal,
scale);
ctx->save_for_backward(
{query,
key,
value,
std::get<0>(outputs),
std::get<1>(outputs),
std::get<2>(outputs)});
variable_list result = {
std::get<0>(outputs), std::get<1>(outputs), std::get<2>(outputs)};
return result;
}
static variable_list backward(
AutogradContext* ctx,
variable_list grad_outputs) {
auto attn_bias = ctx->saved_data["attn_bias"].toOptional<at::Tensor>();
auto dropout_p = ctx->saved_data["dropout_p"].toDouble();
auto is_causal = ctx->saved_data["is_causal"].toBool();
auto scale = ctx->saved_data["scale"].toOptional<double>();
auto compute_grad = ctx->saved_data["attn_bias_requires_grad"].toBool();
auto saved = ctx->get_saved_variables();
Tensor query = saved[0];
Tensor key = saved[1];
Tensor value = saved[2];
Tensor output = saved[3];
Tensor logsumexp = saved[4];
Tensor dropout_mask = saved[5];
auto grad_inputs = ipex_sdp_dropout_backward(
grad_outputs[0],
query,
key,
value,
attn_bias,
output,
logsumexp,
dropout_mask,
dropout_p,
compute_grad,
is_causal,
scale);
return {
std::get<0>(grad_inputs),
std::get<1>(grad_inputs),
std::get<2>(grad_inputs),
std::get<3>(grad_inputs),
Tensor(),
Tensor(),
Tensor(),
Tensor()};
}
};
template <int alignment>
bool is_aligned(const SymInt& size) {
return size % alignment == 0;
}
template <int alignment>
at::Tensor pad_bias(const at::Tensor& attn_bias) {
auto last_dim_size = attn_bias.sym_size(-1);
auto pad_count = alignment - (last_dim_size % alignment);
auto padded_bias = at::pad_symint(attn_bias, {c10::SymInt(0), pad_count});
return padded_bias.slice_symint(-1, 0, last_dim_size);
}
Tensor preprocess_mask(
const Tensor& mask,
const Tensor& query,
const Tensor& key,
const Tensor& value) {
constexpr int mem_eff_alignment = 16;
// Expand to 4d case
at::Tensor attn_mask = mask.expand_symint(
{query.sym_size(0),
query.sym_size(1),
query.sym_size(2),
key.sym_size(2)});
bool aligned_last_dim = is_aligned<mem_eff_alignment>(attn_mask.sym_size(-1));
// Apply pad_bias and store the result in attn_mask
if (!aligned_last_dim) {
return pad_bias<mem_eff_alignment>(attn_mask);
}
// Check and make the tensor contiguous if needed
if (attn_mask.sym_stride(0) % 16 != 0 || attn_mask.sym_stride(1) % 16 != 0 ||
attn_mask.sym_stride(2) % 16 != 0) {
return attn_mask.contiguous();
}
return attn_mask;
}
// We compute dropout mask tensor then pass to forward, and save for backward
Tensor xetla_sdp_dropout(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const c10::optional<at::Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
c10::optional<double> scale) {
c10::optional<Tensor> attn_mask =
sdp::convert_boolean_attn_mask(attn_mask_, query_.dtype());
bool compute_logsumexp =
(query_.requires_grad() || key.requires_grad() || value.requires_grad());
if (attn_mask.has_value()) {
attn_mask.value() = preprocess_mask(attn_mask.value(), query_, key, value);
;
}
auto out_and_lse = IPEXSDPDropoutOp::apply(
query_,
key,
value,
attn_mask,
compute_logsumexp,
dropout_p,
is_causal,
scale);
return out_and_lse[0];
}
int64_t _fused_sdp_choice(
const Tensor& query,
const Tensor& key,
const Tensor& value,
const std::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
std::optional<double> scale,
bool enable_gqa) {
// We have implemented efficient_attention backend with xetla, flash_attention
// backend is not supported now, which will be implemented in the future. So
// we provide two backends here.
sdp::sdp_params kernel_params{
query, key, value, attn_mask_, dropout_p, is_causal, enable_gqa};
sdp::SDPBackend backend = sdp::use_mem_efficient_attention(kernel_params)
? sdp::SDPBackend::efficient_attention
: sdp::SDPBackend::math;
if (backend == sdp::SDPBackend::error) {
TORCH_CHECK(
false,
"No viable backend for scaled_dot_product_attention was found. ",
"This is likely due to turning off both the math kernel and the fused kernels.");
}
return static_cast<int64_t>(backend);
}
inline void validate_sdpa_input(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const c10::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
c10::optional<double> scale) {
TORCH_CHECK(
query_.dtype() == key.dtype() && query_.dtype() == value.dtype(),
"Expected query, key, and value to have the same dtype, but got query.dtype: ",
query_.dtype(),
" key.dtype: ",
key.dtype(),
" and value.dtype: ",
value.dtype(),
" instead.");
TORCH_CHECK(
query_.device() == key.device() && query_.device() == value.device(),
"Expected query, key, and value to have the same device type, but got query.device: ",
query_.device(),
" key.device: ",
key.device(),
" and value.device: ",
value.device(),
" instead.");
TORCH_CHECK(
query_.dim() >= 2 && key.dim() >= 2 && value.dim() >= 2,
"Expected query, key, and value to all be at least 2 dimensional, but got query.dim: ",
query_.dim(),
" key.dim: ",
key.dim(),
" and value.dim: ",
value.dim(),
" instead.");
if (attn_mask_.has_value()) {
auto mask_dtype = attn_mask_->dtype();
TORCH_CHECK(
mask_dtype == at::kBool || mask_dtype == query_.dtype(),
"Expected attn_mask dtype to be bool or to match query dtype, but got attn_mask.dtype: ",
mask_dtype,
" and query.dtype: ",
query_.dtype(),
" instead.");
}
return;
}
bool check_if_xetla_valid_for_varlen(const at::Tensor& query, int head_dim) {
if (query.scalar_type() == at::kHalf || query.scalar_type() == at::kBFloat16)
return head_dim * 2 % 128 == 0;
return false;
}
std::tuple<Tensor, Tensor> _scaled_dot_product_attention_varlen_math(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const c10::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
const c10::optional<Tensor>& dropout_mask,
c10::optional<double> scale,
c10::optional<double> softcap) {
C10_LOG_API_USAGE_ONCE("torch.sdpa.math_fallback");
if (query_.is_nested() || key.is_nested() || value.is_nested()) {
TORCH_CHECK(
query_.is_contiguous() && key.is_contiguous() && value.is_contiguous(),
"scaled_dot_product_attention: If inputs are nested tensors they must be contiguous");
}
auto attn_mask = attn_mask_;
// Naive, composite implementation defined here.
// Scale q, k before matmul for stability see https://tinyurl.com/sudb9s96 for
// math
bool is_negative_scaling = scale.has_value() && scale.value() < 0.0;
const auto scaling_factor =
sdp::calculate_scale(
query_, is_negative_scaling ? std::abs(scale.value()) : scale)
.sqrt();
const auto query = query_ *
(is_negative_scaling ? c10::SymFloat(0.0) - scaling_factor
: scaling_factor);
at::Tensor causal_mask;
if (is_causal) {
TORCH_CHECK(
!query.is_nested() && !key.is_nested(),
"_scaled_dot_product_attention: Nested tensors for query / key are not supported when is_causal=True");
// Replace attn_mask with causal mask; lower triangular elements take part
// in attention.
const auto L = query.sym_size(-2), S = key.sym_size(-2);
causal_mask =
at::ones_symint({L, S}, query.options().dtype(at::kBool)).tril();
causal_mask =
sdp::convert_boolean_attn_mask(causal_mask, query.dtype()).value();
}
auto attn = at::matmul(query, key.transpose(-2, -1) * scaling_factor);
if (softcap.value() > 0.0) {
attn = c10::SymFloat(softcap.value()) *
at::tanh(attn / c10::SymFloat(softcap.value()));
}
if (attn_mask.has_value() && !is_causal) {
if (at::areAnyTensorSubclassLike({attn, *attn_mask})) {
attn = attn.add(*attn_mask);
} else {
attn.add_(*attn_mask);
}
}
if (causal_mask.defined() && !attn_mask.has_value()) {
if (at::areAnyTensorSubclassLike({attn, causal_mask})) {
attn = attn.add(causal_mask);
} else {
attn.add_(causal_mask);
}
}
attn = at::softmax(attn, -1);
if (dropout_p > 0.0) {
if (dropout_mask.has_value()) {
// In order to validate the correctness of the fused kernels, we need to
// use the same dropout mask in order to compare the results.
TORCH_WARN_ONCE("Dropout mask should only be used for testing purposes.");
attn = attn.masked_fill(dropout_mask->logical_not(), 0.0);
auto dropout_scaling = 1.0 / (1 - dropout_p);
return std::make_tuple(at::matmul(attn, value * dropout_scaling), attn);
} else {
attn = at::dropout(attn, dropout_p, true);
}
}
return std::make_tuple(at::matmul(attn, value), attn);
}
Tensor varlen_fwd_math_impl(
const at::Tensor& query, // [batch, seqlen, query_heads, head_dim]
const at::Tensor& key, // [batch, seqlen, key_heads, head_dim]
const at::Tensor& value, // [batch, seqlen, key_heads, head_dim]
Tensor& out_, // same as query
const at::Tensor& cu_seqlens_q, // [batch + 1]
const at::Tensor& cu_seqlens_k, // [batch + 1]
const c10::optional<at::Tensor>& seqused_k,
const c10::optional<at::Tensor>&
alibi_slopes_, // [num_heads] | [batch, num_heads]
const int32_t num_queries,
const int32_t num_keys,
const int32_t batch_size,
const int32_t num_heads,
const int32_t num_heads_kv,
const int32_t head_dims,
const int64_t max_seqlen_q,
const int64_t max_seqlen_k,
const double p_dropout,
const double softmax_scale,
const bool zero_tensors,
bool is_causal,
const bool return_softmax,
const double softcap) {
// Get the length of each sequences in query
TORCH_CHECK(
!alibi_slopes_.has_value(),
"IPEX varlen fwd math implementation do not support alibi when head_dim * sizeof(dtype) not 128 byte aligned.");
TORCH_CHECK(
!is_causal,
"IPEX varlen fwd do not support causal when head_dim * sizeof(dtype) not 128 byte aligned.")
at::Tensor q_len_1 = cu_seqlens_q.slice(0, 1, cu_seqlens_q.size(0), 1);
at::Tensor q_len_2 = cu_seqlens_q.slice(0, 0, cu_seqlens_q.size(0) - 1, 1);
at::Tensor seqlen_q = q_len_1 - q_len_2;
// Get the length of each sequences in key
at::Tensor k_len_1 = cu_seqlens_k.slice(0, 1, cu_seqlens_k.size(0), 1);
at::Tensor k_len_2 = cu_seqlens_k.slice(0, 0, cu_seqlens_k.size(0) - 1, 1);
at::Tensor seqlen_k = k_len_1 - k_len_2;
// Generate index sequence by max_selqen_q and expand it to [batch_size,
// max_seqlen_q] for qkv
at::Tensor q_mask =
at::arange(0, max_seqlen_q, query.options().device(query.device()))
.view({1, max_seqlen_q})
.repeat({batch_size, 1});
at::Tensor k_mask =
at::arange(0, max_seqlen_k, key.options().device(key.device()))
.view({1, max_seqlen_k})
.repeat({batch_size, 1});
// Generate bool mask for data select in padding tensor
seqlen_q = seqlen_q.view({batch_size, 1}).repeat({1, max_seqlen_q});
seqlen_k = seqlen_k.view({batch_size, 1}).repeat({1, max_seqlen_k});
q_mask = q_mask < seqlen_q;
k_mask = k_mask < seqlen_k;
// construct padding tensors for qkv
at::Tensor pad_q = at::zeros(
{batch_size, max_seqlen_q, num_heads, head_dims},
query.options().dtype(query.scalar_type()).device(query.device()));
at::Tensor pad_k = at::zeros(
{batch_size, max_seqlen_k, num_heads_kv, head_dims},
key.options().dtype(key.scalar_type()).device(key.device()));
at::Tensor pad_v = at::zeros(
{batch_size, max_seqlen_k, num_heads_kv, head_dims},
value.options().dtype(value.scalar_type()).device(value.device()));
// Put unpad data to padding tensor
pad_q.index_put_({q_mask}, query);
pad_k.index_put_({k_mask}, key);
pad_v.index_put_({k_mask}, value);
// in case of the difference for kv_head and query_head
TORCH_CHECK(
num_heads_kv <= num_heads,
"Num_heads_kv should be less or equal than num_heads.");
if (num_heads_kv < num_heads) {
TORCH_CHECK(
num_heads % num_heads_kv == 0,
"Num_heads_kv should be divisible by num_heads.");
int divide_ratio = num_heads / num_heads_kv;
pad_k = pad_k.view({batch_size, max_seqlen_k, num_heads_kv, 1, head_dims})
.repeat({1, 1, 1, divide_ratio, 1})
.view({batch_size, max_seqlen_k, num_heads, head_dims});
pad_v = pad_v.view({batch_size, max_seqlen_k, num_heads_kv, 1, head_dims})
.repeat({1, 1, 1, divide_ratio, 1})
.view({batch_size, max_seqlen_k, num_heads, head_dims});
}
// generate attention mask for softmax
at::Tensor attn_mask = at::full(
{batch_size, 1, 1, max_seqlen_k},
double(-1 * INFINITY),
query.options().dtype(query.scalar_type()).device(query.device()));
attn_mask.masked_fill_(k_mask.view({batch_size, 1, 1, max_seqlen_k}), 0);
// convert to [batch, num_heads, seqlen, head_dim]
pad_q = pad_q.permute({0, 2, 1, 3});
pad_k = pad_k.permute({0, 2, 1, 3});
pad_v = pad_v.permute({0, 2, 1, 3});
at::Tensor out =
std::get<0>(AtenIpexTypeXPU::_scaled_dot_product_attention_varlen_math(
pad_q,
pad_k,
pad_v,
attn_mask,
p_dropout,
is_causal,
c10::nullopt,
softmax_scale,
softcap));
// convert back to [batch, seqlen, num_heas, head_dim]
out = out.permute({0, 2, 1, 3}).index({q_mask});
out_.copy_(out);
return out_;
}
Tensor varlen_fwd(
const at::Tensor& query, // [num_tokens_q, query_heads, head_dim]
const at::Tensor& key, // [num_tokens_k, key_heads, head_dim]
const at::Tensor& value, // [num_tokens_k, seqlen, key_heads, head_dim]
Tensor& out_, // same as query