forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmbeddingBag.cpp
1776 lines (1649 loc) · 69.2 KB
/
EmbeddingBag.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
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include <ATen/Dispatch.h>
#include <ATen/Parallel.h>
#include <ATen/TensorOperators.h>
#include <ATen/TensorSubclassLikeUtils.h>
#include <ATen/TensorUtils.h>
#include <ATen/cpu/vec/vec.h>
#include <ATen/native/EmbeddingBag.h>
#include <ATen/native/CPUBlas.h>
#include <ATen/native/NonSymbolicBC.h>
#include <c10/util/irange.h>
#include <c10/util/Half.h>
#ifdef USE_FBGEMM
#include <fbgemm/Fbgemm.h>
#include <fbgemm/FbgemmConvert.h>
#else
#include <caffe2/perfkernels/embedding_lookup_idx.h>
#endif
#include <cstring>
#include <tuple>
#include <utility>
#include <vector>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#include <ATen/NativeFunctions.h>
#else
#include <ATen/ops/_embedding_bag.h>
#include <ATen/ops/_embedding_bag_backward_native.h>
#include <ATen/ops/_embedding_bag_dense_backward.h>
#include <ATen/ops/_embedding_bag_dense_backward_native.h>
#include <ATen/ops/_embedding_bag_forward_only.h>
#include <ATen/ops/_embedding_bag_forward_only_native.h>
#include <ATen/ops/_embedding_bag_native.h>
#include <ATen/ops/_embedding_bag_per_sample_weights_backward_native.h>
#include <ATen/ops/_embedding_bag_sparse_backward.h>
#include <ATen/ops/_embedding_bag_sparse_backward_native.h>
#include <ATen/ops/embedding_backward_native.h>
#include <ATen/ops/embedding_bag_native.h>
#include <ATen/ops/empty.h>
#include <ATen/ops/max.h>
#include <ATen/ops/ones_like.h>
#include <ATen/ops/resize_native.h>
#include <ATen/ops/zero_native.h>
#include <ATen/ops/zeros.h>
#endif
namespace at::native {
template<typename scalar_t>
scalar_t dot_impl(int64_t n, scalar_t *x, int64_t incx, scalar_t *y, int64_t incy);
static void make_offset2bag(const Tensor &offsets, Tensor& offset2bag) {
offset2bag.index_add_(
0, offsets, at::ones_like(offsets, LEGACY_CONTIGUOUS_MEMORY_FORMAT)); // offset2bag = [1 0 1 0 1]
offset2bag[0] -= 1; // offset2bag = [0 0 1 0 1]
offset2bag = offset2bag.cumsum(0, offset2bag.scalar_type()); // offset2bag = [0 0 1 1 2]
}
namespace {
std::pair<c10::MaybeOwned<Tensor>, c10::MaybeOwned<Tensor>> promoteIndicesAndOffsets(
const Tensor& indices,
const Tensor& offsets) {
const auto commonType =
promoteTypes(offsets.scalar_type(), indices.scalar_type());
return {
indices.scalar_type() == commonType ? c10::MaybeOwned<Tensor>::borrowed(indices)
: c10::MaybeOwned<Tensor>::owned(indices.toType(commonType)),
offsets.scalar_type() == commonType ? c10::MaybeOwned<Tensor>::borrowed(offsets)
: c10::MaybeOwned<Tensor>::owned(offsets.toType(commonType))};
}
// Determines if we can use a fast implementation for index_select_add, which
// is only applicable if special conditions are met
template<typename index_t>
bool is_fast_path_index_select(const Tensor& src, Tensor& output, index_t padding_idx) {
return (src.scalar_type() == kFloat || src.scalar_type() == kHalf ||
src.scalar_type() == kBFloat16) &&
src.strides()[1] == 1 && output.strides()[1] == 1 &&
padding_idx < static_cast<index_t>(0);
}
// Determines if we can use a fast implementation for index_select_scale_add,
// which is only applicable if special conditions are met
template<typename index_t>
bool is_fast_path_index_select_scale(const Tensor& src, const Tensor& scale, Tensor& output, index_t padding_idx) {
return (src.scalar_type() == kFloat || src.scalar_type() == kHalf ||
src.scalar_type() == kBFloat16) &&
src.strides()[1] == 1 && output.strides()[1] == 1 &&
scale.strides()[0] == 1 && padding_idx < static_cast<index_t>(0);
}
template<typename index_t>
bool is_fast_path(const Tensor& src, const std::optional<Tensor>& scale, Tensor& output, index_t padding_idx) {
return (scale.has_value() && scale.value().defined()) ?
is_fast_path_index_select_scale(src, scale.value(), output, padding_idx) :
is_fast_path_index_select(src, output, padding_idx);
}
// This function combines index_select (using select_indices as the index) and
// index_add (using add_indices as the index), without creating an intermediary
// tensor to hold the selected embeddings
template <typename data_t, typename index_t>
static std::enable_if_t<std::is_same_v<data_t, double>, void>
index_select_add(
const Tensor& select_indices,
const Tensor& add_indices,
const Tensor& src,
Tensor& output,
const Tensor& /*offsets*/,
bool /*include_last_offset*/,
Tensor& bag_size,
index_t padding_idx,
_EmbeddingBagKernelCache* /* fbgemm_kernel_cache */) {
TORCH_CHECK(select_indices.numel() == add_indices.numel());
auto* add_indices_data = add_indices.const_data_ptr<index_t>();
auto* select_indices_data = select_indices.const_data_ptr<index_t>();
auto* src_data = src.const_data_ptr<data_t>();
auto* output_data = output.data_ptr<data_t>();
index_t* bag_size_data = nullptr;
if (bag_size.defined()) {
bag_size_data = bag_size.data_ptr<index_t>();
}
auto numel = add_indices.numel();
int64_t ddim = src.size(1);
auto vocab_size = src.size(0);
auto src_stride0 = src.strides()[0];
auto src_stride1 = src.strides()[1];
auto output_stride0 = output.strides()[0];
auto output_stride1 = output.strides()[1];
for (const auto i : c10::irange(numel)) {
// We can skip indices equal to padding_idx so they are not included in
// the reduction
auto idx = select_indices_data[i];
TORCH_CHECK(
idx >= 0 && idx < vocab_size,
"embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ",
idx);
if (idx != padding_idx) {
at::native::cpublas::axpy<data_t>(ddim, 1,
src_data + src_stride0 * idx, src_stride1,
output_data + output_stride0 * add_indices_data[i], output_stride1);
} else if (bag_size_data) {
// Decrement bag_size to reflect that the index is padded
bag_size_data[add_indices_data[i]]--;
}
}
}
namespace {
template <typename index_t>
void fbgemm_spmdm_report_error_(
int64_t output_size,
int index_size,
int64_t N,
const index_t* offsets,
const index_t* indices) {
for (const auto m : c10::irange(output_size)) {
for (index_t i = offsets[m]; i < offsets[m + 1]; ++i) {
TORCH_CHECK(i < index_size);
index_t idx = indices[i];
TORCH_CHECK(
0 <= idx && idx < N,
"Index ",
i,
" of input takes value ",
idx,
" which is not in the valid range [0, ",
N,
")");
}
}
TORCH_CHECK(
offsets[output_size] == index_size,
"Your input appears to be incorrect: the last offset value should be "
"the size of the indices tensor, but it seems not to be the case.");
}
} // namespace
template <typename data_t, typename index_t>
std::enable_if_t<
std::is_same_v<data_t, at::Half> || std::is_same_v<data_t, at::BFloat16>,
void>
index_select_add(
const Tensor& select_indices,
const Tensor& add_indices,
const Tensor& src,
Tensor& output,
const Tensor& offsets,
bool include_last_offset,
Tensor& bag_size,
index_t padding_idx,
_EmbeddingBagKernelCache* fbgemm_kernel_cache) {
int64_t ddim = src.size(1);
auto* select_indices_data = select_indices.const_data_ptr<index_t>();
auto* output_data = output.data_ptr<data_t>();
if (is_fast_path_index_select(src, output, padding_idx)) {
auto src_contig = src.contiguous();
auto* src_data = src_contig.const_data_ptr<data_t>();
int64_t output_size = offsets.numel() - 1;
auto* offsets_data = offsets.const_data_ptr<index_t>();
std::vector<index_t> offsets_include_last;
if (include_last_offset) {
output_size = offsets.numel() - 1;
} else {
output_size = offsets.numel();
offsets_include_last.resize(offsets.numel() + 1);
if (offsets.numel() > 0) {
std::memcpy(
offsets_include_last.data(),
offsets.const_data_ptr<index_t>(),
sizeof(index_t) * offsets.numel());
}
offsets_include_last[offsets.numel()] = select_indices.numel();
offsets_data = offsets_include_last.data();
}
#if defined(USE_FBGEMM)
constexpr bool isbf16 = std::is_same_v<data_t, at::Half> ? false : true;
auto kernel_16bit_index_t = fbgemm_kernel_cache
? fbgemm_kernel_cache
->getCallback</* has_weight */ false, index_t, uint16_t>(ddim)
: fbgemm::GenerateEmbeddingSpMDM<uint16_t, index_t, index_t, uint16_t>(
/* block_size */ ddim,
/* has_weight */ false,
/* normalize_by_lengths */ false,
/* prefetch */ 16,
/* is_weight_positional */ false,
/* use_offsets */ true,
/* is_bf16_out */ isbf16,
/* is_bf16_in */ isbf16);
at::parallel_for(
0, output_size, 1, [&](index_t start_idx, index_t end_idx) {
bool success = kernel_16bit_index_t(
/* output_size */ end_idx - start_idx,
/* index_size */ offsets_data[end_idx] - offsets_data[start_idx],
/* data_size */ src.size(0),
/* input */ reinterpret_cast<const uint16_t*>(src_data),
/* indices */ select_indices_data + offsets_data[start_idx],
/* offsets_or_lengths */ offsets_data + start_idx,
/* weights */ nullptr,
/* output */
reinterpret_cast<uint16_t*>(output_data + start_idx * ddim));
if (!success) {
fbgemm_spmdm_report_error_(
end_idx - start_idx,
offsets_data[end_idx] - offsets_data[start_idx],
src.size(0),
offsets_data + start_idx,
select_indices_data + offsets_data[start_idx]);
}
});
#else
// Initialize the intermediate output buffer to be 0.
Tensor output_fp32 = at::zeros({output_size, ddim}, output.options().dtype(at::kFloat));
auto* output_data_fp32 = output_fp32.data_ptr<float>();
using bVec = vec::Vectorized<BFloat16>;
using fVec = vec::Vectorized<float>;
at::parallel_for(
0, output_size, 1, [&](index_t start_idx, index_t end_idx) {
caffe2::EmbeddingLookupIdx(
/*block_size=*/ddim,
/*output_size=*/end_idx - start_idx,
/*index_size=*/offsets_data[end_idx] - offsets_data[start_idx],
/*data_size=*/src.size(0),
/*input=*/src_data,
/*indices=*/select_indices_data + offsets_data[start_idx],
/*offsets=*/offsets_data + start_idx,
/*weights=*/nullptr,
/*scale_bias=*/nullptr,
/*normalize_by_lengths=*/false,
/*out=*/output_data_fp32 + start_idx * ddim);
for (int64_t i = start_idx; i < end_idx; i++) {
// Convert FP32 intermediate buffer result back to 16 bit for
// output dtype
if constexpr (std::is_same_v<data_t, at::Half>) {
// FP16
for (const auto d : c10::irange(ddim)) {
(output_data + i * ddim)[d] =
static_cast<data_t>((output_data_fp32 + ddim * i)[d]);
}
} else {
// BF16
int64_t d = 0;
for (; d < ddim - (ddim % bVec::size()); d += bVec::size()) {
fVec temp_fp32_0 = fVec::loadu(output_data_fp32 + ddim * i + d);
fVec temp_fp32_1 =
fVec::loadu(output_data_fp32 + ddim * i + d + fVec::size());
convert_float_bfloat16(temp_fp32_0, temp_fp32_1)
.store(output_data + i * ddim + d);
}
for (; d < ddim; d++) {
(output_data + i * ddim)[d] =
static_cast<data_t>((output_data_fp32 + ddim * i)[d]);
}
}
}
});
#endif
} else {
TORCH_CHECK(select_indices.numel() == add_indices.numel());
auto* src_data = src.const_data_ptr<data_t>();
auto* add_indices_data = add_indices.const_data_ptr<index_t>();
index_t* bag_size_data = nullptr;
if (bag_size.defined()) {
bag_size_data = bag_size.data_ptr<index_t>();
}
auto vocab_size = src.size(0);
auto src_stride0 = src.strides()[0];
auto src_stride1 = src.strides()[1];
auto output_stride0 = output.strides()[0];
auto output_stride1 = output.strides()[1];
auto numel = add_indices.numel();
Tensor src_fp32 = at::empty({ddim}, src.options().dtype(at::kFloat));
auto* src_data_fp32 = src_fp32.mutable_data_ptr<float>();
// Initialize the intermediate output buffer to be 0.
Tensor output_fp32 =
at::zeros({output.size(0), ddim}, output.options().dtype(at::kFloat));
auto* output_data_fp32 = output_fp32.data_ptr<float>();
for (const auto i : c10::irange(numel)) {
// We can skip indices equal to padding_idx so they are not included in
// the reduction
auto idx = select_indices_data[i];
TORCH_CHECK(
idx >= 0 && idx < vocab_size,
"embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ",
idx);
if (idx != padding_idx) {
// Copy src_data + src_stride0 * idx to src_data_fp32
for (const auto d : c10::irange(ddim)) {
src_data_fp32[d] = static_cast<float>(
(src_data + src_stride0 * idx)[d * src_stride1]);
}
at::native::cpublas::axpy<float>(
ddim,
1,
src_data_fp32,
1,
output_data_fp32 + ddim * add_indices_data[i],
1);
} else if (bag_size_data) {
// Decrement bag_size to reflect that the index is padded
bag_size_data[add_indices_data[i]]--;
}
}
for (const auto i : c10::irange(output.size(0))) {
// Convert FP32 intermediate buffer result back to 16 bit for output
// dtype
for (const auto d : c10::irange(ddim)) {
(output_data + output_stride0 * i)[d * output_stride1] =
static_cast<data_t>((output_data_fp32 + ddim * i)[d]);
}
}
}
}
template<typename data_t, typename index_t>
std::enable_if_t<std::is_same_v<data_t, float>, void>
index_select_add(const Tensor &select_indices,
const Tensor &add_indices,
const Tensor &src,
Tensor &output,
const Tensor& offsets,
bool include_last_offset,
Tensor &bag_size,
index_t padding_idx,
_EmbeddingBagKernelCache* fbgemm_kernel_cache) {
int64_t ddim = src.size(1);
auto* select_indices_data = select_indices.const_data_ptr<index_t>();
auto* output_data = output.data_ptr<float>();
if (is_fast_path_index_select(src, output, padding_idx)) {
auto src_contig = src.contiguous();
auto* src_data = src_contig.const_data_ptr<float>();
int64_t output_size = offsets.numel() - 1;
auto* offsets_data = offsets.const_data_ptr<index_t>();
std::vector<index_t> offsets_include_last;
if (include_last_offset) {
output_size = offsets.numel() - 1;
} else {
output_size = offsets.numel();
offsets_include_last.resize(offsets.numel() + 1);
if (offsets.numel() > 0) {
std::memcpy(
offsets_include_last.data(),
offsets.const_data_ptr<index_t>(),
sizeof(index_t) * offsets.numel());
}
offsets_include_last[offsets.numel()] = select_indices.numel();
offsets_data = offsets_include_last.data();
}
#ifdef USE_FBGEMM
auto kernel_fp32_index_t =
fbgemm_kernel_cache ?
fbgemm_kernel_cache->getCallback</* has_weight */ false, index_t, float>(ddim) :
fbgemm::GenerateEmbeddingSpMDM<float, index_t, index_t>(
/* block_size */ddim,
/* has_weight */false,
/* normalize_by_lengths */false,
/* prefetch */16,
/* is_weight_positional */false,
/* use_offsets */true
);
#endif
at::parallel_for(
0, output_size, 1, [&](index_t start_idx, index_t end_idx) {
#ifdef USE_FBGEMM
bool success = kernel_fp32_index_t(
/* output_size */end_idx - start_idx,
/* index_size */offsets_data[end_idx] - offsets_data[start_idx],
/* data_size */src.size(0),
/* input */src_data,
/* indices */select_indices_data + offsets_data[start_idx],
/* offsets_or_lengths */offsets_data + start_idx,
/* weights */nullptr,
/* output */output_data + start_idx * ddim);
if (!success) {
fbgemm_spmdm_report_error_(
end_idx - start_idx,
offsets_data[end_idx] - offsets_data[start_idx],
src.size(0),
offsets_data + start_idx,
select_indices_data + offsets_data[start_idx]);
}
#else
caffe2::EmbeddingLookupIdx(
/*block_size=*/ddim,
/*output_size=*/end_idx - start_idx,
/*index_size=*/offsets_data[end_idx] - offsets_data[start_idx],
/*data_size=*/src.size(0),
/*input=*/src_data,
/*indices=*/select_indices_data + offsets_data[start_idx],
/*offsets=*/offsets_data + start_idx,
/*weights=*/nullptr,
/*scale_bias=*/nullptr,
/*normalize_by_lengths=*/false,
/*out=*/output_data + start_idx * ddim);
#endif
});
} else {
AT_ASSERT(select_indices.numel() == add_indices.numel());
auto* src_data = src.const_data_ptr<float>();
auto* add_indices_data = add_indices.const_data_ptr<index_t>();
index_t* bag_size_data = nullptr;
if (bag_size.defined()) {
bag_size_data = bag_size.data_ptr<index_t>();
}
auto vocab_size = src.size(0);
auto src_stride0 = src.strides()[0];
auto src_stride1 = src.strides()[1];
auto output_stride0 = output.strides()[0];
auto output_stride1 = output.strides()[1];
auto numel = add_indices.numel();
for (const auto i : c10::irange(numel)) {
// We can skip indices equal to padding_idx so they are not included in
// the reduction
auto idx = select_indices_data[i];
TORCH_CHECK(
idx >= 0 && idx < vocab_size,
"embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ",
idx);
if (idx != padding_idx) {
at::native::cpublas::axpy<float>(
ddim,
1,
src_data + src_stride0 * idx,
src_stride1,
output_data + output_stride0 * add_indices_data[i],
output_stride1);
} else if (bag_size_data) {
// Decrement bag_size to reflect that the index is padded
bag_size_data[add_indices_data[i]]--;
}
}
}
}
// This function fuses the following three fns:
// index_select (using select_indices as the index)
// mul (scaling by per_sample_weights)
// index_add (using add_indices as the index)
template <typename data_t, typename index_t>
static std::enable_if_t<std::is_same_v<data_t, double>, void>
index_select_scale_add(
const Tensor& select_indices,
const Tensor& add_indices,
const Tensor& scale,
const Tensor& src,
Tensor& output,
const Tensor& /*offsets*/,
bool /*include_last_offset*/,
Tensor& bag_size,
index_t padding_idx,
_EmbeddingBagKernelCache* /* fbgemm_kernel_cache */) {
AT_ASSERT(select_indices.numel() == add_indices.numel());
auto* add_indices_data = add_indices.const_data_ptr<index_t>();
auto* select_indices_data = select_indices.const_data_ptr<index_t>();
auto* src_data = src.const_data_ptr<data_t>();
auto* output_data = output.data_ptr<data_t>();
index_t* bag_size_data = nullptr;
if (bag_size.defined()) {
bag_size_data = bag_size.data_ptr<index_t>();
}
auto numel = add_indices.numel();
int64_t ddim = src.size(1);
auto vocab_size = src.size(0);
auto src_stride0 = src.strides()[0];
auto src_stride1 = src.strides()[1];
auto output_stride0 = output.strides()[0];
auto output_stride1 = output.strides()[1];
auto* scale_data = scale.const_data_ptr<data_t>();
auto scale_stride = scale.strides()[0];
for (const auto i : c10::irange(numel)) {
// We can skip indices equal to padding_idx so they are not included in
// the reduction
auto idx = select_indices_data[i];
TORCH_CHECK(
idx >= 0 && idx < vocab_size,
"embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ",
idx);
if (idx != padding_idx) {
auto* src_base = src_data + src_stride0 * idx;
auto* output_base = output_data + output_stride0 * add_indices_data[i];
auto scale = scale_data[i * scale_stride];
for (const auto j : c10::irange(ddim)) {
output_base[j * output_stride1] += src_base[j * src_stride1] * scale;
}
} else if (bag_size_data) {
// Decrement bag_size to reflect that the index is padded
bag_size_data[add_indices_data[i]]--;
}
}
}
template <typename data_t, typename index_t>
std::enable_if_t<
std::is_same_v<data_t, at::Half> || std::is_same_v<data_t, at::BFloat16>,
void>
index_select_scale_add(
const Tensor& select_indices,
const Tensor& add_indices,
const Tensor& scale,
const Tensor& src,
Tensor& output,
const Tensor& offsets,
bool include_last_offset,
Tensor& bag_size,
index_t padding_idx,
_EmbeddingBagKernelCache* fbgemm_kernel_cache) {
int64_t ddim = src.size(1);
auto* scale_data = scale.const_data_ptr<data_t>();
auto* select_indices_data = select_indices.const_data_ptr<index_t>();
auto* output_data = output.data_ptr<data_t>();
if (is_fast_path_index_select_scale(src, scale, output, padding_idx)) {
auto src_contig = src.contiguous();
auto* src_data = src_contig.const_data_ptr<data_t>();
int64_t output_size = offsets.numel() - 1;
auto* offsets_data = offsets.const_data_ptr<index_t>();
std::vector<index_t> offsets_include_last;
if (include_last_offset) {
output_size = offsets.numel() - 1;
} else {
output_size = offsets.numel();
offsets_include_last.resize(offsets.numel() + 1);
std::memcpy(
offsets_include_last.data(),
offsets.const_data_ptr<index_t>(),
sizeof(index_t) * offsets.numel());
offsets_include_last[offsets.numel()] = select_indices.numel();
offsets_data = offsets_include_last.data();
}
Tensor scale_fp32 = at::empty(scale.sizes(), scale.options().dtype(at::kFloat));
auto* scale_data_fp32 = scale_fp32.mutable_data_ptr<float>();
#if defined(USE_FBGEMM)
constexpr bool isbf16 = std::is_same_v<data_t, at::Half> ? false : true;
if constexpr (isbf16) {
fbgemm::Bfloat16ToFloat_simd(
reinterpret_cast<const fbgemm::bfloat16*>(scale_data),
scale_data_fp32,
scale_fp32.numel());
} else {
fbgemm::Float16ToFloat_simd(
reinterpret_cast<const fbgemm::float16*>(scale_data),
scale_data_fp32,
scale_fp32.numel());
}
auto kernel_16bit_index_t = fbgemm_kernel_cache
? fbgemm_kernel_cache
->getCallback</* has_weight */ true, index_t, uint16_t>(ddim)
: fbgemm::GenerateEmbeddingSpMDM<uint16_t, index_t, index_t, uint16_t>(
/* block_size */ ddim,
/* has_weight */ true,
/* normalize_by_lengths */ false,
/* prefetch */ 16,
/* is_weight_positional */ false,
/* use_offsets */ true,
/* is_bf16_out */ isbf16,
/* is_bf16_in */ isbf16);
at::parallel_for(
0, output_size, 1, [&](index_t start_idx, index_t end_idx) {
bool success = kernel_16bit_index_t(
/* output_size */ end_idx - start_idx,
/* index_size */ offsets_data[end_idx] - offsets_data[start_idx],
/* data_size */ src.size(0),
/* input */ reinterpret_cast<const uint16_t*>(src_data),
/* indices */ select_indices_data + offsets_data[start_idx],
/* offsets_or_lengths */ offsets_data + start_idx,
/* weights */ scale_data_fp32 + offsets_data[start_idx],
/* output */
reinterpret_cast<uint16_t*>(output_data + start_idx * ddim));
if (!success) {
fbgemm_spmdm_report_error_(
end_idx - start_idx,
offsets_data[end_idx] - offsets_data[start_idx],
src.size(0),
offsets_data + start_idx,
select_indices_data + offsets_data[start_idx]);
}
});
#else
// Initialize the intermediate output buffer to be 0.
Tensor output_fp32 =
at::zeros({output_size, ddim}, output.options().dtype(at::kFloat));
auto* output_data_fp32 = output_fp32.data_ptr<float>();
for (const auto i : c10::irange(scale.numel())) {
scale_data_fp32[i] = static_cast<float>(scale_data[i]);
}
using bVec = vec::Vectorized<BFloat16>;
using fVec = vec::Vectorized<float>;
at::parallel_for(
0, output_size, 1, [&](index_t start_idx, index_t end_idx) {
caffe2::EmbeddingLookupIdx(
/*block_size=*/ddim,
/*output_size=*/end_idx - start_idx,
/*index_size=*/offsets_data[end_idx] - offsets_data[start_idx],
/*data_size=*/src.size(0),
/*input=*/src_data,
/*indices=*/select_indices_data + offsets_data[start_idx],
/*offsets=*/offsets_data + start_idx,
/*weights=*/scale_data_fp32 + offsets_data[start_idx],
/*scale_bias=*/nullptr,
/*normalize_by_lengths=*/false,
/*out=*/output_data_fp32 + start_idx * ddim);
for (int64_t i = start_idx; i < end_idx; i++) {
// Convert FP32 intermediate buffer result back to 16 bit for
// output dtype
if constexpr (std::is_same_v<data_t, at::Half>) {
// FP16
for (const auto d : c10::irange(ddim)) {
(output_data + i * ddim)[d] =
static_cast<data_t>((output_data_fp32 + ddim * i)[d]);
}
} else {
// BF16
int64_t d = 0;
for (; d < ddim - (ddim % bVec::size()); d += bVec::size()) {
fVec temp_fp32_0 = fVec::loadu(output_data_fp32 + ddim * i + d);
fVec temp_fp32_1 =
fVec::loadu(output_data_fp32 + ddim * i + d + fVec::size());
convert_float_bfloat16(temp_fp32_0, temp_fp32_1)
.store(output_data + i * ddim + d);
}
for (; d < ddim; d++) {
(output_data + i * ddim)[d] =
static_cast<data_t>((output_data_fp32 + ddim * i)[d]);
}
}
}
});
#endif
} else {
AT_ASSERT(select_indices.numel() == add_indices.numel());
auto* src_data = src.const_data_ptr<data_t>();
auto* add_indices_data = add_indices.const_data_ptr<index_t>();
index_t* bag_size_data = nullptr;
if (bag_size.defined()) {
bag_size_data = bag_size.data_ptr<index_t>();
}
auto vocab_size = src.size(0);
auto src_stride0 = src.strides()[0];
auto src_stride1 = src.strides()[1];
auto output_stride0 = output.strides()[0];
auto output_stride1 = output.strides()[1];
auto scale_stride = scale.strides()[0];
auto numel = add_indices.numel();
// Initialize the intermediate output buffer to be 0.
Tensor output_fp32 =
at::zeros({output.size(0), ddim}, output.options().dtype(at::kFloat));
auto* output_data_fp32 = output_fp32.data_ptr<float>();
for (const auto i : c10::irange(numel)) {
// We can skip indices equal to padding_idx so they are not included in
// the reduction
auto idx = select_indices_data[i];
TORCH_CHECK(
idx >= 0 && idx < vocab_size,
"embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ",
idx);
if (idx != padding_idx) {
auto* src_base = src_data + src_stride0 * idx;
auto* output_base_fp32 = output_data_fp32 + ddim * add_indices_data[i];
auto scale = scale_data[i * scale_stride];
for (const auto j : c10::irange(ddim)) {
output_base_fp32[j] += static_cast<float>(src_base[j * src_stride1]) *
static_cast<float>(scale);
}
} else if (bag_size_data) {
// Decrement bag_size to reflect that the index is padded
bag_size_data[add_indices_data[i]]--;
}
}
for (const auto i : c10::irange(output.size(0))) {
// Convert FP32 intermediate buffer result back to 16 bit for output
// dtype
for (const auto d : c10::irange(ddim)) {
(output_data + output_stride0 * i)[d * output_stride1] =
static_cast<data_t>((output_data_fp32 + ddim * i)[d]);
}
}
}
}
template<typename data_t, typename index_t>
std::enable_if_t<std::is_same_v<data_t, float>, void>
index_select_scale_add(const Tensor &select_indices,
const Tensor &add_indices,
const Tensor &scale,
const Tensor &src,
Tensor &output,
const Tensor& offsets,
bool include_last_offset,
Tensor &bag_size,
index_t padding_idx,
_EmbeddingBagKernelCache* fbgemm_kernel_cache) {
int64_t ddim = src.size(1);
auto* scale_data = scale.const_data_ptr<float>();
auto* select_indices_data = select_indices.const_data_ptr<index_t>();
auto* output_data = output.data_ptr<float>();
if (is_fast_path_index_select_scale(src, scale, output, padding_idx)) {
auto src_contig = src.contiguous();
auto* src_data = src_contig.const_data_ptr<float>();
int64_t output_size = offsets.numel() - 1;
auto* offsets_data = offsets.const_data_ptr<index_t>();
std::vector<index_t> offsets_include_last;
if (include_last_offset) {
output_size = offsets.numel() - 1;
} else {
output_size = offsets.numel();
offsets_include_last.resize(offsets.numel() + 1);
std::memcpy(
offsets_include_last.data(),
offsets.const_data_ptr<index_t>(),
sizeof(index_t) * offsets.numel());
offsets_include_last[offsets.numel()] = select_indices.numel();
offsets_data = offsets_include_last.data();
}
#ifdef USE_FBGEMM
auto kernel_fp32_index_t =
fbgemm_kernel_cache ?
fbgemm_kernel_cache->getCallback</* has_weight */ true, index_t, float>(ddim) :
fbgemm::GenerateEmbeddingSpMDM<float, index_t, index_t>(
/* block_size */ddim,
/* has_weight */true,
/* normalize_by_lengths */false,
/* prefetch */16,
/* is_weight_positional */false,
/* use_offsets */true
);
#endif
at::parallel_for(
0, output_size, 1, [&](index_t start_idx, index_t end_idx) {
#ifdef USE_FBGEMM
bool success = kernel_fp32_index_t(
/* output_size */end_idx - start_idx,
/* index_size */offsets_data[end_idx] - offsets_data[start_idx],
/* data_size */src.size(0),
/* input */src_data,
/* indices */select_indices_data + offsets_data[start_idx],
/* offsets_or_lengths */offsets_data + start_idx,
/* weights */scale_data + offsets_data[start_idx],
/* output */output_data + start_idx * ddim);
if (!success) {
fbgemm_spmdm_report_error_(
end_idx - start_idx,
offsets_data[end_idx] - offsets_data[start_idx],
src.size(0),
offsets_data + start_idx,
select_indices_data + offsets_data[start_idx]);
}
#else
caffe2::EmbeddingLookupIdx(
/*block_size=*/ddim,
/*output_size=*/end_idx - start_idx,
/*index_size=*/offsets_data[end_idx] - offsets_data[start_idx],
/*data_size=*/src.size(0),
/*input=*/src_data,
/*indices=*/select_indices_data + offsets_data[start_idx],
/*offsets=*/offsets_data + start_idx,
/*weights=*/scale_data + offsets_data[start_idx],
/*scale_bias=*/nullptr,
/*normalize_by_lengths=*/false,
/*out=*/output_data + start_idx * ddim);
#endif
});
} else {
AT_ASSERT(select_indices.numel() == add_indices.numel());
auto* src_data = src.const_data_ptr<float>();
auto* add_indices_data = add_indices.const_data_ptr<index_t>();
index_t* bag_size_data = nullptr;
if (bag_size.defined()) {
bag_size_data = bag_size.data_ptr<index_t>();
}
auto vocab_size = src.size(0);
auto src_stride0 = src.strides()[0];
auto src_stride1 = src.strides()[1];
auto output_stride0 = output.strides()[0];
auto output_stride1 = output.strides()[1];
auto scale_stride = scale.strides()[0];
auto numel = add_indices.numel();
for (const auto i : c10::irange(numel)) {
// We can skip indices equal to padding_idx so they are not included in
// the reduction
auto idx = select_indices_data[i];
TORCH_CHECK(
idx >= 0 && idx < vocab_size,
"embedding_bag: Expected idx >= 0 && idx < num_embeddings but found idx to be ",
idx);
if (idx != padding_idx) {
auto* src_base = src_data + src_stride0 * idx;
auto* output_base = output_data + output_stride0 * add_indices_data[i];
auto scale = scale_data[i * scale_stride];
for (const auto j : c10::irange(ddim)) {
output_base[j * output_stride1] += src_base[j * src_stride1] * scale;
}
} else if (bag_size_data) {
// Decrement bag_size to reflect that the index is padded
bag_size_data[add_indices_data[i]]--;
}
}
}
}
} // namespace
void check_arguments(
const Tensor& weight,
const Tensor& indices,
const Tensor& offsets,
const int64_t mode,
const std::optional<Tensor>& per_sample_weights,
bool include_last_offset) {
auto indices_arg = TensorArg(indices, "indices", 1);
checkScalarTypes("embedding_bag", indices_arg, {kLong, kInt});
auto offsets_arg = TensorArg(offsets, "offsets", 1);
checkScalarTypes("embedding_bag", offsets_arg, {kLong, kInt});
checkSameType("embedding_bag", indices_arg, offsets_arg);
auto weight_arg = TensorArg(weight, "weight", 1);
checkScalarTypes(
"embedding_bag", weight_arg, {kHalf, kBFloat16, kFloat, kDouble});
AT_DISPATCH_INDEX_TYPES(offsets.scalar_type(), "_embedding_bag_cpu_impl", [&]() {
if (offsets.size(0) > 0) {
index_t offset_0 = offsets.const_data_ptr<index_t>()[0];
index_t offset_n = offsets.const_data_ptr<index_t>()[offsets.size(0)-1];
TORCH_CHECK(offset_0 == 0, "offsets[0] has to be 0, i.e., the first sequence "
"in the mini-batch has to start from position 0. "
"However, got ", offsets[0]);
TORCH_CHECK(offset_n <= indices.size(0), "offsets[-1] can not "
"be greater than input's length ", indices.size(0), " but got offsets[-1] of ",
offset_n);
}
});
if (per_sample_weights.has_value() && per_sample_weights.value().defined()) {
TORCH_CHECK(
mode == EmbeddingBagMode::SUM,
"embedding_bag: per_sample_weights only supported with mode='sum'");
auto per_input_weights_arg = TensorArg(
per_sample_weights.value(),"per_sample_weights", 1);
checkSameType("embedding_bag", weight_arg, per_input_weights_arg);
TORCH_CHECK(per_sample_weights.value().dim() == 1);
TORCH_CHECK(per_sample_weights.value().numel() == indices.numel());
}
if (include_last_offset) {
TORCH_CHECK(
offsets.size(0) >= 1,
"include_last_offset: number of offset should be at least 1");
}
}
void make_bag_size_out(
Tensor& bag_size_out,
const Tensor& offsets,
const Tensor& indices,
const int64_t mode,
const bool include_last_offset,
const bool requires_grad) {
if (requires_grad || mode == EmbeddingBagMode::MEAN ||
mode == EmbeddingBagMode::MAX) {
auto num_bags = offsets.size(0) - (include_last_offset ? 1 : 0);
at::native::resize_(bag_size_out, {num_bags}, std::nullopt);
// Compute this for EmbeddingBagMode::MEAN and EmbeddingBagMode::MAX (latter
// needed for backwards)
if (num_bags != 1) {
bag_size_out.slice(0, 0, bag_size_out.size(0) - 1, 1) =
offsets.slice(0, 1, num_bags, 1) -
offsets.slice(0, 0, num_bags - 1, 1);
}
if (num_bags > 0) {
bag_size_out[-1] = indices.size(0) - offsets[num_bags - 1];
}
} else {
at::native::resize_(bag_size_out, offsets.sizes(), std::nullopt);
}
}
void make_max_indices_out(
Tensor& max_indices_out,
const Tensor& weight,
const Tensor& indices,
const Tensor& offsets,
const Tensor& bag_size,
const int64_t mode,
bool include_last_offset) {
int64_t numBags = offsets.size(0);
if (mode == EmbeddingBagMode::MAX) {
if (include_last_offset) {
TORCH_CHECK(
numBags >= 1, "include_last_offset: numBags should be at least 1");
numBags -= 1;
}
at::native::resize_(max_indices_out, {numBags, weight.sizes()[1]}, std::nullopt);
at::native::zero_(max_indices_out);
} else {
at::native::resize_(max_indices_out, bag_size.sizes(), std::nullopt);
}
}
void make_offset2bag_out(
Tensor& offset2bag,
Tensor& output,
const Tensor& weight,
const Tensor& indices,
const Tensor& offsets,
const int64_t mode,
const std::optional<Tensor>& per_sample_weights,
const int64_t padding_idx) {
// To save compute, if we are going to go down the fast path case for the 'sum'
// mode, we skip calculating offset2bag, since it is not going to be used.
bool fast_path_sum = is_fast_path(weight, per_sample_weights, output, padding_idx);
if (mode == EmbeddingBagMode::MEAN || mode == EmbeddingBagMode::MAX ||
!fast_path_sum) {
at::native::resize_(offset2bag, {indices.size(0) + 1}, std::nullopt);
at::native::zero_(offset2bag);
int64_t offsets_size = offsets.size(0);
bool include_last_offset = (output.size(0) == offsets_size - 1);
// when include_last_offset is true, ignore the last index in offset.
// fix segfault when include_last_offset is true and offsets[-1] != indices.size(0)
// see https://github.com/pytorch/pytorch/issues/89677 for more details.
Tensor _offsets = offsets;
if (include_last_offset) {
_offsets = offsets.narrow(0, 0, offsets_size - 1);
}
make_offset2bag(_offsets, offset2bag);
at::native::resize_(offset2bag, {indices.size(0)}, std::nullopt);
// only initialize output in slow path
at::native::zero_(output);
}
}
static Tensor make_bag_size(
const Tensor& offsets,
const Tensor& indices,
const int64_t mode,