-
Notifications
You must be signed in to change notification settings - Fork 127
/
tensor_operators.cpp
executable file
·1578 lines (1310 loc) · 46.1 KB
/
tensor_operators.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
/* All or part of this file was contributed by Intel under license:
* Copyright (C) 2017-2018 Intel Corporation
* SPDX-License-Identifier: MIT
*/
#include "tensors/tensor_operators.h"
#include "tensors/cpu/backend.h"
#include "tensors/allocator.h"
#include "functional/approx.h"
#include "functional/functional.h"
#include "functional/tensor.h"
#include "functional/operators.h"
#if MKL_FOUND
#include <mkl.h>
#endif
namespace marian {
namespace cpu {
void IsNaN(const Tensor /*in*/, Ptr<Allocator> /*allocator*/, bool& /*isNaN*/, bool& /*isInf*/) {
ABORT("Not implemented");
}
template <typename To, typename From>
void CopyCastTo(To* out, const From* in, int length) {
for(int i = 0; i < length; ++i)
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4244) // 'argument': conversion from 'const From' to 'float', possible loss of data
#endif
out[i] = (To)in[i];
#ifdef _MSC_VER
#pragma warning (pop)
#endif
}
// Casting has been factored into two functions "CopyCastFrom" and
// "CopyCastTo". This only serves the purpuse to automatically create
// the full Carthesian product of possible type cast via template magic.
// Extending CopyCast and CopyCastFrom with a new branch in the "if" clause
// adds all possible variants.
template <typename T>
void CopyCastFrom(Tensor out, const T* in, int length) {
if(out->type() == Type::float32) {
CopyCastTo(out->data<float>(), in, length);
} else if(out->type() == Type::float16) {
CopyCastTo(out->data<float16>(), in, length);
} else {
ABORT("CopyCastTo to type {} not implemented", out->type());
}
}
// currently useless on the CPU until more types are added
void CopyCast(Tensor out, const Tensor in) {
if(in->type() == Type::float32) {
CopyCastFrom(out, in->data<float>(), (int)in->size());
} else if(in->type() == Type::float16) {
CopyCastFrom(out, in->data<float16>(), (int)in->size());
} else if(in->type() == Type::uint32) {
CopyCastFrom(out, in->data<uint32_t>(), (int)in->size());
} else {
ABORT("CopyCastFrom from type {} not implemented", in->type());
}
}
void ConcatCont(Tensor out, const std::vector<Tensor>& inputs, int axis) {
int step = 1;
for(int i = 0; i < axis; ++i)
step *= out->shape()[i];
size_t offset1 = 0;
for(int i = 0; i < step; ++i) {
for(auto in : inputs) {
size_t size = in->shape().elements() / step;
size_t offset2 = i * size;
std::copy(in->data() + offset2,
in->data() + offset2 + size,
out->data() + offset1);
offset1 += size;
}
}
}
template <bool add>
inline void gInsertCols(float* out,
const float* in,
size_t rows,
size_t cols,
size_t cols_out,
size_t cols_in,
size_t offset_out,
size_t offset_in) {
for(size_t j = 0; j < rows; ++j) {
float* rowOut = out + j * cols_out + offset_out;
const float* rowIn = in + j * cols_in + offset_in;
for(size_t i = 0; i < cols; ++i) {
if(add) // this was solved earlier via beta * rowOut[i] with beta in {0,1} but 0 * nan in uninitialized tensors will result in nan.
rowOut[i] += rowIn[i];
else
rowOut[i] = rowIn[i];
}
}
}
void Concatenate1(Tensor out, const std::vector<Tensor>& inputs) {
int rows = out->shape().elements() / out->shape().back();
size_t offset = 0;
int cols_out = out->shape().back();
for(auto in : inputs) {
ABORT_IF(rows != in->shape().elements() / in->shape().back(),
"First dimension must be equal");
int cols_in = in->shape().back();
cpu::gInsertCols<false>(out->data(),
in->data(),
rows,
cols_in,
cols_out,
cols_in,
offset,
0);
offset += cols_in;
}
}
void Concatenate(Tensor out, const std::vector<Tensor>& inputs, int ax) {
if(ax == (int)out->shape().size() - 1)
Concatenate1(out, inputs);
else
ConcatCont(out, inputs, ax);
}
void Split1(std::vector<Tensor>& outputs, const Tensor in) {
size_t offset = 0;
int rows = in->shape().elements() / in->shape().back();
int cols_in = in->shape().back();
for(auto out : outputs) {
ABORT_IF(rows != out->shape().elements() / out->shape().back(),
"First dimension must be equal");
int cols_out = out->shape().back();
// set last parameter to 1 to enable += instead of =
// @TODO: do this in a more principled ways accross all/most kernels
cpu::gInsertCols<true>(out->data(),
in->data(),
rows,
cols_out,
cols_out,
cols_in,
0,
offset);
offset += cols_out;
}
}
void SplitCont(std::vector<Tensor>& outputs, const Tensor in, int axis) {
int step = 1;
for(int i = 0; i < axis; ++i)
step *= in->shape()[i];
size_t offset1 = 0;
for(int i = 0; i < step; ++i) {
for(auto out : outputs) {
size_t size = out->shape().elements() / step;
size_t offset2 = i * size;
// BUG: This overwrites gradients!
// std::copy(in->data() + offset1,
// in->data() + offset1 + size,
// out->data() + offset2);
// Fixes gradient problem, @TODO: check performance
std::transform(in->data() + offset1,
in->data() + offset1 + size,
out->data() + offset2,
out->data() + offset2,
[](float a, float b) { return a + b; });
offset1 += size;
}
}
}
void Deconcatenate(std::vector<Tensor>& outputs, const Tensor in, int ax) {
if(ax == (int)in->shape().size() - 1)
Split1(outputs, in);
else
SplitCont(outputs, in, ax);
}
template <bool add>
void Transpose0213(Tensor out, Tensor in) {
int cols = in->shape()[-1];
int rows = in->shape().elements() / in->shape()[-1];
int r1 = in->shape()[-2];
int r2 = in->shape()[-3];
int rest = rows / (r1 * r2);
for(int k = 0; k < rest; ++k) {
int shift = k * r1 * r2;
for(int j = 0; j < r1 * r2; ++j) {
int src = j + shift;
int dst = j / r1 + (j % r1) * r2 + shift;
const float* inRow = in->data() + src * cols;
float* outRow = out->data() + dst * cols;
if(!add) {
// mostly for fast forward computation
std::copy(inRow, inRow + cols, outRow);
} else {
for(int i = 0; i < cols; ++i) {
outRow[i] += inRow[i];
}
}
}
}
}
// This function is called only when MKL is available.
#if MKL_FOUND
// Given a 4D array, transpose (swap) the initial 3 dimensions while keeping the last dimension.
// e.g. 1234 --> 2134, 1234 --> 3214 (4 is always kept).
// This is an optimized version for swapping first 3 dimensions
// assuming the last dimension is large enough to get benefits from vectorized copy.
//
// @param out output tensor
// @param in input tensor
// @param vAxis target (transposed) axes of each given axes
template <bool add>
void TransposeFirst3In4(Tensor out, Tensor in, const std::vector<int>& vAxis) {
ABORT_IF(vAxis.size() != 4, "This function handles only 4D arrays.");
int innermost = in->shape()[-1];
int l1 = in->shape()[vAxis[0]];
int l2 = in->shape()[vAxis[1]];
int l3 = in->shape()[vAxis[2]];
// find the mapping between the transposed output dimensional indices (oi, oj, ok)
// and original input dimensional indices (i, j, k)
int oi, oj, ok;
#pragma omp parallel for
for(int k = 0; k < l1; ++k) {
int shift = k * l2 * l3;
for(int j = 0; j < l2; ++j) {
for(int i = 0; i < l3; ++i) {
if(vAxis[0] == 0) {
if(vAxis[1] == 1) {
oi = i; oj = j; ok = k;
} else {
oi = j; oj = i; ok = k;
}
} else if(vAxis[0] == 1) {
if(vAxis[1] == 0) {
oi = i; oj = k; ok = j;
} else {
oi = j; oj = k; ok = i;
}
} else {
if(vAxis[1] == 0) {
oi = k; oj = i; ok = j;
} else {
oi = k; oj = j; ok = i;
}
}
int src = ok * in->shape()[1] * in->shape()[2] + oj * in->shape()[2] + oi;
int dst = l3 * j + shift + i;
const float* inRow = in->data() + src * innermost;
float* outRow = out->data() + dst * innermost;
if(!add) {
mkl_somatcopy('R', 'N', 1, innermost, 1.0f, inRow, innermost, outRow, innermost);
} else {
for(int ii = 0; ii < innermost; ++ii) {
outRow[ii] += inRow[ii];
}
}
}
}
}
}
#endif // MKL_FOUND
inline void transpose4x4_SSE(const float* A,
float* B,
const int lda,
const int ldb) {
__m128 row1 = _mm_load_ps(&A[0 * lda]);
__m128 row2 = _mm_load_ps(&A[1 * lda]);
__m128 row3 = _mm_load_ps(&A[2 * lda]);
__m128 row4 = _mm_load_ps(&A[3 * lda]);
_MM_TRANSPOSE4_PS(row1, row2, row3, row4);
_mm_store_ps(&B[0 * ldb], row1);
_mm_store_ps(&B[1 * ldb], row2);
_mm_store_ps(&B[2 * ldb], row3);
_mm_store_ps(&B[3 * ldb], row4);
}
// from
// https://stackoverflow.com/questions/16737298/what-is-the-fastest-way-to-transpose-a-matrix-in-c
#define ROUND_UP(x, s) (((x) + ((s)-1)) & -(s))
void Transpose10(Tensor out, const Tensor in) {
const float* A = in->data();
float* B = out->data();
const int n = in->shape().elements() / in->shape()[-1];
const int m = in->shape()[-1];
const int block_size = 16;
int lda = ROUND_UP(m, block_size);
int ldb = ROUND_UP(n, block_size);
for(int i = 0; i < n; i += block_size) {
for(int j = 0; j < m; j += block_size) {
int max_i2 = i + block_size < n ? i + block_size : n;
int max_j2 = j + block_size < m ? j + block_size : m;
for(int i2 = i; i2 < max_i2; i2 += 4) {
for(int j2 = j; j2 < max_j2; j2 += 4) {
transpose4x4_SSE(&A[i2 * lda + j2], &B[j2 * ldb + i2], lda, ldb);
}
}
}
}
}
// @TODO: optimize this, currently it's quite horrible
template <bool add>
void TransposeGeneric(Tensor out, Tensor in, const std::vector<int>& vAxis) {
functional::Array<int, functional::Shape::size()> permute;
int diff = int(functional::Shape::size() - vAxis.size());
for(int i = 0; i < permute.size(); ++i)
if(i < diff)
permute[i] = i;
else
permute[i] = vAxis[i - diff] + diff;
int length = out->shape().elements();
constexpr size_t N = functional::Shape::size();
functional::Array<int, N> oDims;
functional::Array<int, N> pDims;
functional::Tensor<float> gOut = out;
functional::Tensor<float> gIn = in;
for(int index = 0; index < length; ++index) {
gOut.shape().dims(index, oDims);
for(size_t i = 0; i < N; ++i)
pDims[permute[i]] = oDims[i];
// @TODO: where does this change come from?
int inIndex = gIn.shape().index(pDims);
// @TODO: use internal conversion instead of raw indices
if(add)
gOut.data()[index] += gIn.data()[inIndex];
else
gOut.data()[index] = gIn.data()[inIndex];
}
}
void TransposeND(Tensor out, Tensor in, const std::vector<int>& vAxis) {
if(vAxis == std::vector<int>({0, 2, 1, 3}))
Transpose0213<false>(out, in);
#if MKL_FOUND
else if(vAxis.size() == 4 && vAxis[3] == 3)
TransposeFirst3In4<false>(out, in, vAxis);
#endif // MKL_FOUND
else if(vAxis == std::vector<int>({1, 0}) && in->shape()[-1] % 16 == 0
&& in->shape()[-2] % 16 == 0)
Transpose10(out, in);
else
TransposeGeneric<false>(out, in, vAxis);
}
void TransposeNDGrad(Tensor out, Tensor in, const std::vector<int>& vAxis) {
if(vAxis == std::vector<int>({0, 2, 1, 3}))
Transpose0213<true>(out, in);
else
TransposeGeneric<true>(out, in, vAxis);
}
template <typename ElementType>
void Softmax(Tensor out, Tensor in) {
using namespace functional;
functional::Tensor<ElementType> fout = out;
const functional::Tensor<ElementType> fin = in;
ElementType* pOut = fout.data();
const ElementType* pIn = fin.data();
int rows = fout.shape().elements() / fout.shape().back();
int cols = fout.shape().back();
for(int j = 0; j < rows; ++j) {
ElementType* so = pOut + j * cols;
const ElementType* sp = pIn + j * cols;
ElementType max = sp[0];
for(int i = 1; i < cols; ++i) {
max = Ops<ElementType>::max(max, sp[i]);
}
// if ElementType is a complex type, e.g. float32x8, find the max of these 8 values
typename Ops<ElementType>::Single maxs = Ops<ElementType>::maxReduce(max);
ElementType sum = 0.f;
for(int i = 0; i < cols; ++i) {
ElementType ex = Ops<ElementType>::exp(Ops<ElementType>::sub(sp[i], maxs));
sum = Ops<ElementType>::add(sum, ex);
so[i] = ex;
}
// if ElementType is a complex type, e.g. float32x8, sum these 8 values
typename Ops<ElementType>::Single sums = Ops<ElementType>::sumReduce(sum);
for(int i = 0; i < cols; ++i) {
so[i] = Ops<ElementType>::div(so[i], sums);
}
}
}
void Softmax(Tensor out, Tensor in) {
matchOrAbort<float>(out->type());
matchOrAbort<float>(in->type());
#ifdef __AVX__
if(out->shape()[-1] % 8 == 0) {
Softmax<float32x8>(out, in);
return;
}
#endif
if(out->shape()[-1] % 4 == 0) {
Softmax<float32x4>(out, in);
} else {
Softmax<float>(out, in);
}
}
template <typename ElementType>
void LogSoftmax(Tensor out, Tensor in) {
using namespace functional;
functional::Tensor<ElementType> fout = out;
const functional::Tensor<ElementType> fin = in;
ElementType* pOut = fout.data();
const ElementType* pIn = fin.data();
int rows = fout.shape().elements() / fout.shape().back();
int cols = fout.shape().back();
for(int j = 0; j < rows; ++j) {
ElementType* so = pOut + j * cols;
const ElementType* sp = pIn + j * cols;
ElementType max = sp[0];
for(int i = 1; i < cols; ++i) {
max = Ops<ElementType>::max(max, sp[i]);
}
typename Ops<ElementType>::Single maxs = Ops<ElementType>::maxReduce(max); // global maximum
ElementType sum = 0.f;
for(int i = 0; i < cols; ++i) {
ElementType sm = Ops<ElementType>::sub(sp[i], maxs);
sum = Ops<ElementType>::add(sum, Ops<ElementType>::exp(sm));
so[i] = sm;
}
typename Ops<ElementType>::Single sums = Ops<ElementType>::sumReduce(sum); // global sum
ElementType logSum = Ops<ElementType>::log(sums); // broadcasts Single to ElementType
for(int i = 0; i < cols; ++i) {
so[i] = Ops<ElementType>::sub(so[i], logSum);
}
}
}
void LogSoftmax(Tensor out, Tensor in) {
matchOrAbort<float>(out->type());
matchOrAbort<float>(in->type());
#ifdef __AVX__
if(out->shape()[-1] % 8 == 0) {
LogSoftmax<float32x8>(out, in);
return;
}
#endif
if(out->shape()[-1] % 4 == 0) {
LogSoftmax<float32x4>(out, in);
} else {
LogSoftmax<float>(out, in);
}
}
// @TODO: Remove remaining underscores in CPU kernels
void SoftmaxGrad(Tensor grad_, Tensor adj_, Tensor val_) {
int rows = grad_->shape().elements() / grad_->shape()[-1];
int cols = grad_->shape()[-1];
float* grad = grad_->data();
const float* adj = adj_->data();
const float* val = val_->data();
for(int j = 0; j < rows; ++j) {
float* gradRow = grad + j * cols;
const float* adjRow = adj + j * cols;
const float* valRow = val + j * cols;
float sum = 0.f;
for(int i = 0; i < cols; ++i) {
sum += valRow[i] * adjRow[i];
}
for(int i = 0; i < cols; ++i) {
gradRow[i] += valRow[i] * (adjRow[i] - sum);
}
}
}
void LogSoftmaxGrad(Tensor grad_, Tensor adj_, Tensor val_) {
int rows = grad_->shape().elements() / grad_->shape()[-1];
int cols = grad_->shape()[-1];
float* grad = grad_->data();
const float* adj = adj_->data();
const float* val = val_->data();
for(int j = 0; j < rows; ++j) {
float* gradRow = grad + j * cols;
const float* adjRow = adj + j * cols;
const float* valRow = val + j * cols;
float sum = 0.f;
for(int i = 0; i < cols; ++i) {
sum += adjRow[i];
}
for(int i = 0; i < cols; ++i) {
gradRow[i] += adjRow[i] - sum * expf(valRow[i]);
}
}
}
void CopyRows(Tensor out_,
const Tensor in_,
const Tensor indices) {
matchOrAbort<IndexType>(indices->type());
size_t cols = in_->shape()[-1];
size_t rows = indices->size();
// note: may also be applied to IndexType; works by luck. Fix with fp16
float* out = out_->data();
const float* in = in_->data();
#pragma omp parallel for
for(size_t j = 0; j < rows; ++j) {
size_t dst = j;
// @TODO: consider moving type checking to this function
// instead of matchOrAbort above
size_t src = (size_t)indices->data<IndexType>()[j];
float* rowOut = out + dst * cols;
const float* rowIn = in + src * cols;
std::copy(rowIn, rowIn + cols, rowOut);
}
}
void PasteRows(Tensor out_,
const Tensor in_,
const Tensor indices) {
matchOrAbort<IndexType>(indices->type());
size_t cols = in_->shape()[-1];
size_t rows = indices->size();
float* out = out_->data();
const float* in = in_->data();
for(size_t j = 0; j < rows; ++j) {
size_t dst = indices->data<IndexType>()[j]; // not a permutation - may alias, unlike PasteCols
size_t src = j;
float* rowOut = out + dst * cols;
const float* rowIn = in + src * cols;
for(size_t i = 0; i < cols; ++i) {
rowOut[i] += rowIn[i];
}
}
}
void CopyCols(Tensor out_,
const Tensor in_,
const Tensor indices) {
matchOrAbort<IndexType>(indices->type());
size_t rows = in_->shape().elements() / in_->shape()[-1];
size_t colsIn = in_->shape()[-1];
size_t colsOut = indices->size();
float* out = out_->data();
const float* in = in_->data();
#pragma omp parallel for
for(size_t j = 0; j < rows; ++j) {
const float* rowIn = in + j * colsIn;
float* rowOut = out + j * colsOut;
for(size_t i = 0; i < colsOut; ++i) {
rowOut[i] = rowIn[indices->data<IndexType>()[i]];
}
}
}
void PasteCols(Tensor out_,
const Tensor in_,
const Tensor indices) {
matchOrAbort<IndexType>(indices->type());
size_t rows = out_->shape().elements() / out_->shape()[-1];
size_t colsOut = out_->shape()[-1];
size_t colsIn = indices->size();
float* out = out_->data();
const float* in = in_->data();
/* n.b. Unlike PasteRows, currently appears safe to assume indices[i] is a
* permutation i.e. no racy aliases, and no need to sum vs. just assign.
*/
for(size_t j = 0; j < rows; ++j) {
const float* rowIn = in + j * colsIn;
float* rowOut = out + j * colsOut;
for(size_t i = 0; i < colsIn; ++i) {
rowOut[indices->data<IndexType>()[i]] += rowIn[i];
}
}
}
#if 0 // this version seems to actually be buggy, but also not used in decoding?
// Optimized version of Select for axis=2
// @TODO: make this generally fast without this special version
void SelectAxis2(Tensor out,
const Tensor in,
const Tensor indices) {
std::cerr << indices->debug() << std::endl;
matchOrAbort<IndexType>(indices->type());
functional::Shape outShape = out->shape();
functional::Shape inShape = in->shape();
auto idxData = indices->data<IndexType>();
auto odata = out->data();
const auto idata = in->data();
int size = outShape[3];
for(int k = 0; k < outShape[0]; ++k) {
for(int j = 0; j < outShape[1]; ++j) {
int outOffset = k * j * outShape[2] * size + j * outShape[2] * size;
int inOffset = k * j * inShape[2] * size + j * inShape[2] * size;
for(int i = 0; i < outShape[2]; ++i) {
auto idx = idxData[i];
int outIndex = outOffset + i * size;
int inIndex = inOffset + idx * size;
std::copy(idata + inIndex, idata + inIndex + size, odata + outIndex);
}
}
}
}
#endif
void Select(Tensor out,
const Tensor in,
const Tensor indices,
int axis) {
matchOrAbort<IndexType>(indices->type());
// @TODO: make this efficient
functional::Shape outShape = out->shape();
functional::Shape inShape = in->shape();
functional::Shape idxShape = indices->shape();
int length = outShape.elements();
functional::Array<int, functional::Shape::size()> dims;
int axisCPU = (int)(axis + functional::Shape::size() - out->shape().size());
#if 0 // buggy but not really used?
if(axisCPU == 2 && outShape == idxShape) // specialization for axis==2 when there is no broadcasting, @TODO to be removed once we have a faster implementation below
return SelectAxis2(out, in, indices);
#endif
for(int index = 0; index < length; ++index) {
outShape.dims(index, dims); // compute dimension-based indices from global index;
int idxIndex = idxShape.bindex(dims); // return global index for indices based on dimension-specific indices from out, take broadcasting into account;
dims[axisCPU] = (int)indices->data<IndexType>()[idxIndex]; // substitute index of out-tensor with corresponding axis-local position from in-tensor;
int inIndex = inShape.index(dims); // compute global index from dimension-specific indices, no broadcasting as out and in match in all dimensions apart from axis
out->data()[index] = in->data()[inIndex]; // assign corresponding values.
}
}
void Insert(Tensor out,
const Tensor in,
const Tensor indices,
int axis) {
matchOrAbort<IndexType>(indices->type());
// @TODO: make this efficient
functional::Shape outShape = out->shape();
functional::Shape inShape = in->shape();
functional::Shape idxShape = indices->shape();
int length = inShape.elements();
functional::Array<int, functional::Shape::size()> dims;
int axisCPU = (int)(axis + functional::Shape::size() - out->shape().size());
for(int index = 0; index < length; ++index) {
inShape.dims(index, dims);
int idxIndex = idxShape.bindex(dims); // broadcast index into indices tensor
dims[axisCPU] = (int)indices->data<IndexType>()[idxIndex];
int outIndex = outShape.index(dims);
out->data()[outIndex] += in->data()[index];
}
}
void GRUFastForward(Tensor out_, std::vector<Tensor> inputs, bool final) {
int rows = out_->shape().elements() / out_->shape().back();
int cols = out_->shape().back();
float* out = out_->data();
const float* state = inputs[0]->data();
const float* xW = inputs[1]->data();
const float* sU = inputs[2]->data();
const float* b = inputs[3]->data();
const float* mask = inputs.size() > 4 ? inputs[4]->data() : nullptr;
#pragma omp parallel for
for(int j = 0; j < rows; ++j) {
float m = !mask || mask[j];
float* rowOut = out + j * cols;
const float* rowState = state + j * cols;
const float* xWrow = xW + j * cols * 3;
const float* sUrow = sU + j * cols * 3;
#pragma omp simd
for(int i = 0; i < cols; ++i) {
float r = functional::Ops<float>::sigmoid(xWrow[i] + sUrow[i] + b[i]);
int k = i + cols;
float z = functional::Ops<float>::sigmoid(xWrow[k] + sUrow[k] + b[k]);
int l = i + 2 * cols;
float h;
if(final)
h = std::tanh(xWrow[l] + (sUrow[l] + b[l]) * r);
else
h = std::tanh(xWrow[l] + sUrow[l] * r + b[l]);
float o = (1.0f - z) * h + z * rowState[i];
rowOut[i] = m * o + (1 - m) * rowState[i];
}
}
}
void GRUFastBackward(std::vector<Tensor> outputs,
std::vector<Tensor> inputs,
Tensor adj_,
bool final) {
int rows = adj_->shape().elements() / adj_->shape().back();
int cols = adj_->shape().back();
float* outState = outputs[0] ? outputs[0]->data() : nullptr;
float* outXW = outputs[1] ? outputs[1]->data() : nullptr;
float* outSU = outputs[2] ? outputs[2]->data() : nullptr;
float* outB = outputs[3] ? outputs[3]->data() : nullptr;
const float* state = inputs[0]->data();
const float* xW = inputs[1]->data();
const float* sU = inputs[2]->data();
const float* b = inputs[3]->data();
const float* mask = inputs.size() > 4 ? inputs[4]->data() : 0;
const float* adj = adj_->data();
#pragma omp parallel
for(int j = 0; j < rows; ++j) {
float m = !mask || mask[j];
float* rowOutState = outState + j * cols;
float* rowOutXW = outXW + j * cols * 3;
float* rowOutSU = outSU + j * cols * 3;
const float* rowState = state + j * cols;
const float* rowXW = xW + j * cols * 3;
const float* rowSU = sU + j * cols * 3;
const float* rowAdj = adj + j * cols;
#pragma omp for simd nowait
for(int i = 0; i < cols; ++i) {
int k = i + cols;
int l = i + 2 * cols;
float r = functional::Ops<float>::sigmoid(rowXW[i] + rowSU[i] + b[i]);
float z = functional::Ops<float>::sigmoid(rowXW[k] + rowSU[k] + b[k]);
float h;
if(final)
h = std::tanh(rowXW[l] + (rowSU[l] + b[l]) * r);
else
h = std::tanh(rowXW[l] + rowSU[l] * r + b[l]);
float a = rowAdj[i];
float t = (1 - z) * (1 - h * h);
// df/ds
if(outState)
rowOutState[i] += (m * z - m + 1) * a;
// df/d(xW_r) ...
float dfdxW_r = m * r * (1 - r) * t * a;
if(final)
dfdxW_r *= rowSU[l] + b[l];
else
dfdxW_r *= rowSU[l];
if(outXW)
rowOutXW[i] += dfdxW_r;
if(outSU)
rowOutSU[i] += dfdxW_r;
if(outB)
outB[i] += dfdxW_r;
// df/d(xW_z) ...
float dfdxW_z = m * (1 - z) * z * (rowState[i] - h) * a;
if(outXW)
rowOutXW[k] += dfdxW_z;
if(outSU)
rowOutSU[k] += dfdxW_z;
if(outB)
outB[k] += dfdxW_z;
// df/d(xW_x) ...
float dfdxW_x = m * t * a;
if(outXW)
rowOutXW[l] += dfdxW_x;
if(outSU)
rowOutSU[l] += dfdxW_x * r;
if(outB) {
if(final)
outB[l] += dfdxW_x * r;
else
outB[l] += dfdxW_x;
}
}
}
}
void CrossEntropyPick(Tensor out, Tensor in, Tensor labelIndices, float labelSmoothingAlpha = 0.f) {
matchOrAbort<IndexType>(labelIndices->type());
// Shape& outShape = out_->shape();
Shape& inShape = in->shape();
int rows = inShape.elements() / inShape.back();
int cols = inShape.back();
#pragma omp parallel for
for(int j = 0; j < rows; ++j) {
const float* sp = in->data() + j * cols;
float max = sp[0];
#pragma omp simd reduction(max : max)
for(int i = 1; i < cols; ++i) {
max = std::max(max, sp[i]);
}
float sumexp = 0.f;
#pragma omp simd reduction(+ : sum)
for(int i = 0; i < cols; ++i) {
sumexp += std::exp(sp[i] - max);
}
float mean = 0.f;
#pragma omp simd reduction(+ : sum)
for(int i = 0; i < cols; ++i) {
mean += sp[i] - max;
}
mean /= (float)cols;
// Groundtruth label index
IndexType i = labelIndices->data<IndexType>()[j];
// This appears to be safe i.e. that i >= 0 && i < cols is known
float logsumexp = std::log(sumexp);
float ce = logsumexp - sp[i] + max; // -log(p_i) = - logsoftmax(x_i - max) = - (x_i - max) - log(sum_j exp(x_j - max))
float ls = logsumexp - mean;
out->data()[j] = (1.f - labelSmoothingAlpha) * ce + labelSmoothingAlpha * ls;
}
}
void CrossEntropyPickBackward(Tensor out,
Tensor adj,
Tensor in,
Tensor labelIndices,
float labelSmoothingAlpha = 0.f) {
matchOrAbort<IndexType>(labelIndices->type());
Shape& outShape = out->shape();
int rows = outShape.elements() / outShape.back();
int cols = outShape.back();
#pragma omp parallel for
for(int j = 0; j < rows; ++j) {
const float* sp = in->data() + j * cols;
float* so = out->data() + j * cols;
float max = sp[0];
for(int i = 1; i < cols; ++i) {
max = std::max(max, sp[i]);
}
float sumexp = 0.f;
for(int i = 0; i < cols; ++i) {
sumexp += std::exp(sp[i] - max);
}
// cross-entropy
for(int i = 0; i < cols; ++i) {
float sub = (float)(i == (int)labelIndices->data<IndexType>()[j]); // delta, true if label index and column index match
float dce = std::exp(sp[i] - max) / sumexp - sub
+ labelSmoothingAlpha * (sub - 1.f / (float)cols);
so[i] += adj->data()[j] * dce;
}
}
}
float L2Norm(Tensor in, Ptr<Allocator> /*not used*/) {
float sum = 0.f;
size_t size = in->size();
const float* data = in->data();
#pragma omp parallel for simd reduction(+ : sum)
for(size_t i = 0; i < size; ++i) {
sum += data[i] * data[i];
}
return std::sqrt(sum);
}
void Att(Tensor out_, Tensor va_, Tensor context_, Tensor state_) {
float* out = out_->data();
const float* va = va_->data();
const float* ctx = context_->data();
const float* state = state_->data();
int m = out_->shape().elements() / out_->shape().back();
int k = context_->shape()[-1];
int b = context_->shape()[-2];
int t = context_->shape()[-3];
int rows = m;
int cols = k;
#pragma omp parallel for
for(int j = 0; j < rows; ++j) {
const float* vaRow = va;
const float* ctxRow = ctx + (j % (b * t)) * cols;
const float* stateRow = state + ((j / (b * t)) * b + j % b) * cols;
float sum = 0.f;
#pragma omp simd reduction(+ : sum)
for(int i = 0; i < cols; ++i) {
float z = ctxRow[i] + stateRow[i];
sum += std::tanh(z) * vaRow[i];
}
out[j] = sum;
}
}