-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tensor.cpp
2002 lines (1747 loc) · 59.8 KB
/
Tensor.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 <cmath>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <vector>
#include <memory>
#include <list>
#include <string>
#include <sstream>
#include <set>
#include <algorithm>
#include <math.h>
#include <random>
#include <immintrin.h> // SIMD
//#include <intrin.h> // throws an error when compiling with WSL
#include <x86intrin.h>
#include <smmintrin.h>
#include <numeric> // std::accumulate
#include <thread> // std::thread
#include <atomic>
//#include <pthread.h>
#include "Tensor.h"
#include "Substance.h"
#include "Ops.h"
// ----------------------- Forward declare ----------------------------
template <typename F>
void ApplyOpSimple(Tensor& dst, const Tensor& lhs, const Tensor& rhs, F op);
template <typename F>
inline void ApplyOpSimple(Tensor& ret, const Tensor& src, F op);
union U{
__m128 v;
float a[4];
};
template <typename F>
void runOp(int size, F op){
for(int i = 0; i < size; i++){
op(i);
}
}
int Tensor::GetNumWorkers(){
return s_n_workers;
}
void Tensor::SetNumWorkers(int n_workers) {
s_n_workers = n_workers;
}
int Tensor::GetBatchScale() {
return s_batch_scale;
}
void Tensor::SetBatchScale(int batch_scale) {
s_batch_scale = batch_scale;
}
static void GetParallelParams(int size, int& n_workers, int& n_batch,
int& batch_size) {
// Fetch the number of workers
n_workers = Tensor::GetNumWorkers();
if (n_workers <= 0) {
n_workers = static_cast<int>(std::thread::hardware_concurrency());
}
// Compute batch size and it number
n_batch = n_workers * Tensor::GetBatchScale();
batch_size = size / n_batch + (size % n_batch ? 1 : 0);
n_workers = std::min(n_workers, batch_size);
}
template <typename F>
void RunParallel(int size, F op) {
// Decide parallelization parameters
int n_workers = -1, n_batch = -1, batch_size = -1;
GetParallelParams(size, n_workers, n_batch, batch_size);
if (n_workers <= 1) {
// Single execution
for (int i = 0; i < size; i++) {
// Operation
op(i);
}
} else {
// Parallel execution
std::atomic<int> next_batch(0);
std::vector<std::thread> workers(static_cast<size_t>(n_workers));
for (auto&& worker : workers) {
worker = std::thread([ =, &next_batch ]() noexcept {
int batch_cnt = 0;
while ((batch_cnt = next_batch++) < n_batch) {
for (int i = 0; i < batch_size; i++) {
const int idx = batch_size * batch_cnt + i;
if (size <= idx) {
break;
}
// Operation
op(idx);
}
}
});
}
for (auto&& worker : workers) {
worker.join();
}
}
}
template <typename F, typename R>
float RunParallelWithReduce(int size, F op, R reduce, float init_v) {
// Decide parallelization parameters
int n_workers = -1, n_batch = -1, batch_size = -1;
GetParallelParams(size, n_workers, n_batch, batch_size);
if (n_workers <= 1) {
// Single execution
float v = init_v;
for (int i = 0; i < size; i++) {
// Operation with reduction
v = reduce(v, op(i));
}
return v;
} else {
// Parallel execution
std::atomic<int> next_batch(0);
std::vector<std::thread> workers(static_cast<size_t>(n_workers));
std::vector<float> results(workers.size());
for (size_t t = 0; t < workers.size(); t++) {
workers[t] = std::thread([ =, &next_batch, &results ]() noexcept {
int batch_cnt = 0;
float v = init_v;
while ((batch_cnt = next_batch++) < n_batch) {
for (int i = 0; i < batch_size; i++) {
const int idx = batch_size * batch_cnt + i;
if (size <= idx) {
break;
}
// Operation with reduction
v = reduce(v, op(idx));
}
}
results[t] = v;
});
}
for (auto&& worker : workers) {
worker.join();
}
return std::accumulate(results.begin(), results.end(), init_v, reduce);
}
}
// --------------------------------
/// ---=== Initilizers ===---
// --------------------------------
Tensor::~Tensor() = default;
// Create empty (size 0) array
Tensor::Tensor() : values(std::make_shared<Substance>()){};
// Create new tensor from pointer to substance class
Tensor::Tensor(std::shared_ptr<Substance> sub) : values(sub){};
// Shallow copy
//Tensor::Tensor(const Tensor& lhs) = default;
Tensor::Tensor(const Tensor& lhs) = default;
// Move
// Called when std::move() is used
Tensor::Tensor(Tensor&& lhs) noexcept
: values(lhs.values)
, grad(lhs.grad)
, requires_grad_(lhs.requires_grad_)
, ctx(lhs.ctx)
, has_ctx(lhs.has_ctx)
{
//std::cout << "Tensor::Tensor(Tensor&& lhs)\n";
};
// shallow copy
Tensor& Tensor::operator=(const Tensor& lhs) = default;
/** Move
* Data is moved from one tensor object to another (efficiently)
* Old object may be empty afterwards (will probably be destroyed soon)
*/
Tensor& Tensor::operator=(Tensor&& lhs){
values = lhs.values;
grad = lhs.grad;
requires_grad_ = lhs.requires_grad_;
ctx = lhs.ctx;
has_ctx = lhs.has_ctx;
return *this;
}
//Tensor::Tensor(const InitShape& shape) : Tensor(Shape(shape)){};
/**
* Init tensor from a vector describing its shape
*/
Tensor::Tensor(const Shape& shape, bool req_grad){
size_t size = 1;
for (auto&& s : shape){
if (s < 0){
throw std::runtime_error("Invalid shape format (neg)");
}
size *= static_cast<size_t>(s);
}
values = std::make_shared<Substance>(size, shape);
this->requires_grad_ = req_grad;
}
Tensor::Tensor(const Shape& shape, float fill_v, bool req_grad) : Tensor(shape, req_grad) {
fill(fill_v);
//this->requires_grad_ = req_grad;
}
/**
* Init tensor form 1-D vector
*/
Tensor::Tensor(std::vector<float> vec, bool req_grad){
//throw std::runtime_error("Not implemented");
values = std::make_shared<Substance>(vec.size(), std::vector<int>(vec.size()));
for(size_t i = 0; i < vec.size(); i++){
values->vals.get()[i] = vec[i];
}
this->requires_grad_ = req_grad;
};
// ------------ Float list initializers -------------
template <typename FList>
std::list<int> CheckFListShapeImpl(const FList& init_list){
if (init_list.size() == 0){
return {};
}
// Check that all sub-lists have equal shape
auto itr = init_list.begin(); // get first element
auto shape = CheckFListShapeImpl(*itr); // recursively check sub-elements
for (size_t i = 0; i < init_list.size(); i++, itr++){
if (shape != CheckFListShapeImpl(*itr)){
throw std::runtime_error("Initializing shape is invalid. Dimensions are not equal.");
}
}
// Total shape of children
shape.push_front(static_cast<int>(init_list.size()));
return shape;
}
/**
* Base case: if init_list holds only floats
*/
template <>
inline std::list<int> CheckFListShapeImpl(const FloatList<0>& init_list){
return {static_cast<int>(init_list.size())};
}
template <typename FList>
void CopyFListElemsImpl(const FList& init_list, float*& data){
// copy sequentially
for (auto itr = init_list.begin(); itr != init_list.end(); itr++){
CopyFListElemsImpl(*itr, data);
}
}
/**
* Returns the shape of a nested initialiser list
*/
template <typename FList>
Shape CheckFListShape(const FList& init_list){
// Check and get the shape of nested initialiser
const std::list<int>& shape = CheckFListShapeImpl(init_list);
// Cast to vector
return Shape(shape.begin(), shape.end());
}
template <>
void CopyFListElemsImpl(const FloatList<0>& init_list, float*&data){
// Copy sequentially
for(auto&& v : init_list){
*(data++) = v;
}
}
template <typename FList>
void CopyFListElems(const FList& init_list, float* data){
CopyFListElemsImpl(init_list, data);
}
Tensor::Tensor(FloatList<0> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<1> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<2> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<3> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<4> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<5> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<6> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<7> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<8> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
Tensor::Tensor(FloatList<9> init_list) : Tensor(CheckFListShape(init_list)){
CopyFListElems(init_list, values->vals.get());
}
// ---------------- Tensor init of 1's -------------------
Tensor Tensor::Ones(const Shape& shape){
return Tensor(shape, 0.f);
}
/**
* Tensor t = Tensor::Ones(1, 2, 3, 4);
* t.shape() == 1x2x3x4
*/
template <typename... S>
Tensor Tensor::Ones(S... shape){
return Ones({shape...});
}
// ---------------- Random data init ------------------
std::random_device Tensor::s_rand_seed;
std::mt19937 Tensor::s_rand_engine(s_rand_seed());
int Tensor::s_n_workers = Tensor::DEFAULT_N_WORKERS;
int Tensor::s_batch_scale = Tensor::DEFAULT_BATCH_SCALE;
void Tensor::Seed(){
s_rand_engine = std::mt19937(s_rand_seed());
}
void Tensor::Seed(uint32_t seed){
s_rand_engine = std::mt19937(seed);
}
template <typename D, typename R>
Tensor CreateRandomArray(const Shape& shape, D&& dist, R&& rand_engine){
Tensor ret(shape);
ApplyOpSimple(ret, [&]() { return static_cast<float>(dist(rand_engine));});
return ret;
}
Tensor Tensor::Uniform(float low, float high, const Shape& shape){
std::uniform_real_distribution<> dist(low, high);
return CreateRandomArray(shape, dist, s_rand_engine);
}
Tensor Tensor::Uniform(const Shape& shape){
return Uniform(0.f, 1.f, shape);
}
Tensor Tensor::Normal(float loc, float scale, const Shape& shape) {
// Create normal distribution
std::normal_distribution<> dist(loc, scale);
// Create random array
return CreateRandomArray(shape, dist, s_rand_engine);
}
Tensor Tensor::Normal(const Shape& shape) {
return Normal(0.f, 1.f, shape);
}
// ------------------------
/// --- Cast --------------
// ------------------------
Tensor::operator float() const {
if (values->size != 1){
std::cout << "float() values->size = " << values->size << "\n";
throw std::runtime_error("Only size 1 array can be converted to float");
}
return *(values->vals.get());
}
// -------------------------
// ----- Index methods -----
// -------------------------
// shape: 3, 2, 5
// index: 0, 0, 1
float& Tensor::operator[](const Index& index) const {
const Shape& shape = values->shape;
if (index.size() != shape.size()){
throw std::runtime_error("Invalid index size");
}
int i = 0;
for(size_t d = 0; d < index.size(); d++){
i *= shape[d];
// Allow for negative indexing
const int p_idx = (index[d] >= 0) ? index[d] : shape[d] + index[d];
i += p_idx;
}
return *(values->vals.get() + i);
}
// ------------- Basic getters & setters --------------
float& Tensor::operator[](const int index){
if((size_t)index > (values->size - 1)){
throw std::runtime_error("Index out of range.");
}
return values->vals.get()[index];
}
float& Tensor::operator[](const size_t index){
if(index > (values->size - 1)){
throw std::runtime_error("Index out of range.");
}
return values->vals.get()[index];
}
/**
* Total length of raw data array
*/
size_t Tensor::size() const {
return values->size;
}
/**
* Return pointer to first data element
*/
float* Tensor::id() const{
return values->vals.get();
}
/**
* Return the tensors shape as a string
*/
std::string Tensor::shape_str(){
std::stringstream result;
std::copy(
values->shape.begin(),
values->shape.end(),
std::ostream_iterator<int>(result, " "));
return result.str();
}
const Shape& Tensor::shape() const {
return values->shape;
}
bool Tensor::empty() const {
return values->size == 0;
}
/**
* Number of dimensions
*/
size_t Tensor::ndim() {
return values->shape.size();
}
size_t Tensor::ndim() const{
return values->shape.size();
}
/** Helper
* Fill the data array with some value
*/
void fillN(float* iter, const int n, float fill_v){
runOp(n, [&](int i){ iter[i] = fill_v; });
//RunParallel(n, [&](int i){ iter[i] = fill_v; });
};
/**
* Fill the data array with some value
*/
void Tensor::fill(float v){
fillN(values->vals.get(), static_cast<int>(values->size), v);
}
/*Iter Tensor::begin() {
return Iter(values->vals.get());
}
Iter Tensor::end() {
return Iter(values->vals.get() + values->size);
}*/
float* Tensor::begin(){
return values->begin();
}
float* Tensor::end(){
return values->end();
}
const float* Tensor::begin() const{
return values->begin();
}
const float* Tensor::end() const{
return values->end();
}
float* Tensor::data(){
return begin();
}
const float* Tensor::data() const{
return begin();
}
/**
* Set the requires_grad flag of a tensor (needed when doing floatlist init)
*/
void Tensor::requires_grad(bool req_grad){
this->requires_grad_ = req_grad;
}
/**
* Return bool indicating if gradients are being accumulated for tensor
*/
bool Tensor::requires_grad(){
return this->requires_grad_;
}
bool Tensor::requires_grad() const {
return this->requires_grad_;
}
// --------------------- Applying an operations ------------------
/**
* Apply a simple math operation across two tensors that have the same shape
* Result of the operation is stored in dst tensor
*/
#ifdef SIMD_methods
template <typename F>
void ApplyOpSimple(Tensor& dst, const Tensor& lhs, const Tensor& rhs, F op) {
float* dst_ = dst.id();
float* lhs_ = lhs.id();
float* rhs_ = rhs.id();
auto lhs__ = lhs.data();
auto rhs__ = rhs.data();
auto dst__ = dst.data();
for(size_t i = 0; i < dst.size(); i += 4){
//__m128 a = op(lhs_, rhs_);
__m128 a = _mm_load_ps(&lhs__[i]);
__m128 b = _mm_load_ps(&rhs__[i]);
// TODO: create SIMD methods that take two __m128 vectors
__m128 out = op(a, b);
_mm_store_ps(&dst__[i], out);
}
}
#else
template <typename F>
void ApplyOpSimple(Tensor& dst, const Tensor& lhs, const Tensor& rhs, F op) {
float* dst_ = dst.id();
float* lhs_ = lhs.id();
float* rhs_ = rhs.id();
for(size_t i = 0; i < lhs.size(); i++){
//dst_[i] = lhs_[i] + rhs_[i];
dst_[i] = op(lhs_[i], rhs_[i]);
}
}
#endif
/**
* ApplyOpSimple with only 1 source tensor
*/
template <typename F>
inline void ApplyOpSimple(Tensor& ret, const Tensor& src, F op) {
auto&& ret_data = ret.data();
auto&& src_data = src.data();
// Simply apply all
for(size_t i = 0; i < src.size(); i++){
ret_data[i] = op(src_data[i]);
}
}
/**
* ApplyOpSimple with only a return tensor and a function
*/
template <typename F>
inline void ApplyOpSimple(Tensor& ret, F op) {
auto&& ret_data = ret.data();
for(size_t i = 0; i < ret.size(); i++){
ret_data[i] = op();
}
}
// ---------------------------- Reduce ----------------------------------------
static int ResolveAxis(int axis, size_t ndim, const std::string& name) {
// Resolve negative
const int ndim_i = static_cast<int>(ndim);
if (axis < 0) {
axis = ndim_i + axis;
}
// Check range
if (axis < 0 || ndim_i <= axis) {
std::stringstream ss;
ss << "Invalid axes for " << name;
ss << " (" << ndim << "vs" << axis << ")";
throw std::runtime_error(ss.str());
}
return axis;
}
static Axis ResolveAxis(const Axis& axes, size_t ndim, const std::string& name,
bool sort = false, bool sort_order_normal = true) {
// Resolve for each
Axis ret_axes;
ret_axes.reserve(axes.size());
for (auto&& axis : axes) {
ret_axes.push_back(ResolveAxis(axis, ndim, name));
}
// Sort axes
if (sort) {
if (sort_order_normal) {
// Normal order
std::sort(ret_axes.begin(), ret_axes.end());
} else {
// Inverse order
std::sort(ret_axes.begin(), ret_axes.end(), std::greater<int>());
}
}
return ret_axes;
}
static Shape CheckReductable(const Shape& shape, const Axis& axes,
bool keepdims) {
// Mark reduction axes
std::vector<char> mark(shape.size(), false);
const int n_shape = static_cast<int>(shape.size());
for (auto&& axis : axes) {
if (0 <= axis && axis < n_shape) {
mark[static_cast<size_t>(axis)] = true;
} else {
throw std::runtime_error("Invalid axes for reduction");
}
}
if (keepdims) {
// Pick up unmarked dimension
Shape ret_shape_pad;
for (size_t i = 0; i < mark.size(); i++) {
if (mark[i]) {
ret_shape_pad.push_back(1);
} else {
ret_shape_pad.push_back(shape[i]);
}
}
return ret_shape_pad;
} else {
// No necessary
return {};
}
}
static auto ComputeReduceSizes(const Shape& src_shape, const size_t axis) {
// Compute result shape
Shape ret_shape;
for (size_t dim = 0; dim < src_shape.size(); dim++) {
if (dim != axis) {
ret_shape.push_back(src_shape[dim]);
}
}
if (ret_shape.empty()) { // For all reduction
ret_shape.push_back(1);
}
// Compute sizes
int n_upper = 1, n_lower = 1, n_reduce = 0;
for (size_t dim = 0; dim < src_shape.size(); dim++) {
// Sizes
if (dim < axis) {
n_upper *= src_shape[dim];
} else if (axis < dim) {
n_lower *= src_shape[dim];
} else {
n_reduce = src_shape[dim];
}
}
// Return
return std::make_tuple(std::move(ret_shape), n_upper, n_lower, n_reduce);
}
template <typename F>
float ReduceAxisAll(float * data, const size_t size,
const float init_v, F reduce_op) {
auto&& op = [&](int i) { return data[i]; };
const float ret = RunParallelWithReduce(static_cast<int>(size), op,
reduce_op, init_v);
return ret;
}
template <typename F>
Tensor ReduceAxisOne(const Tensor& src, const size_t axis, const float init_v,
F reduce_op) {
const Shape& src_shape = src.shape();
// Compute sizes
auto reduce_sizes = ComputeReduceSizes(src_shape, axis);
const Shape& ret_shape = std::get<0>(reduce_sizes);
const int n_upper = std::get<1>(reduce_sizes);
const int n_lower = std::get<2>(reduce_sizes);
const int n_reduce = std::get<3>(reduce_sizes);
// Create result array with fill
Tensor ret(ret_shape, init_v);
auto&& src_data = src.data();
auto&& ret_data = ret.data();
// Reduce function
auto&& reduce = [=](int u_idx) {
const int ret_idx_base = u_idx * n_lower;
const int src_idx_base0 = u_idx * n_reduce * n_lower;
for (int redu_idx = 0; redu_idx < n_reduce; redu_idx++) {
const int src_idx_base1 = src_idx_base0 + redu_idx * n_lower;
for (int l_idx = 0; l_idx < n_lower; l_idx++) {
// Reduce
float& r = ret_data[ret_idx_base + l_idx];
const float s = src_data[src_idx_base1 + l_idx];
r = reduce_op(r, s);
}
}
};
// TODO: Run parallel for `axis == 0` (means `n_upper == 1`)
#if 0 // Run in parallel
RunParallel(n_upper, reduce);
#else // Run sequentially
for (int u_idx = 0; u_idx < n_upper; u_idx++) {
reduce(u_idx);
}
#endif
return ret;
}
template <typename F>
Tensor ReduceAxis(Tensor& src, const Axis& axes_raw, bool keepdims,
const float init_v, F reduce_op) {
if (axes_raw.size() == 0) {
// No Axis -> Reduce all
float ret_v = ReduceAxisAll(src.data(), src.size(), init_v, reduce_op);
Tensor ret = {ret_v};
// Reshape for keepdims
if (keepdims) {
Shape ret_shape(src.shape().size(), 1);
ret = ret.reshape(ret_shape);
}
return ret;
} else {
// Resolve axes (sort: on)
const Axis& axes = ResolveAxis(axes_raw, src.ndim(), "Reduce", true);
// Check it is possible to reduce.
Shape src_shape = src.shape();
const Shape& ret_shape_pad = CheckReductable(src_shape, axes, keepdims);
// Reduce axes one by one
Tensor ret;
for (size_t i = 0; i < axes.size(); i++) {
// From back
const size_t axis = static_cast<size_t>(axes[axes.size() - i - 1]);
// Reduce
if (i == 0) {
ret = ReduceAxisOne(src, axis, init_v, reduce_op);
} else {
ret = ReduceAxisOne(ret, axis, init_v, reduce_op);
}
}
// Reshape for keepdims
if (keepdims) {
ret = ret.reshape(ret_shape_pad);
}
return ret;
}
}
Tensor Sum(Tensor& x, const Axis& axes, bool keepdims) {
return ReduceAxis(x, axes, keepdims, 0.f, std::plus<float>());
}
// --------------------- Broadcasting tensors -----------------------
/**
* Return a new shape which allows two tensors have an arithmetic operation applied to them
*/
Shape CheckBroadcastable(const Shape& lhs, const Shape& rhs){
if(lhs.size() < rhs.size()){
// Assume that left tensor is deeper than right tensor
return CheckBroadcastable(rhs, lhs);
}
if(rhs.size() == 0 || (rhs.size() == 1 && rhs[0] == 0)){
throw std::runtime_error("Broadcasting empty array");
}
// lhs: [3, 4, 3, 2]
// rhs: [3, 4, 1]
Shape shape(lhs.size());
// Difference in depth
size_t r_offset = lhs.size() - rhs.size();
for( size_t i = 0; i < lhs.size(); i++ ){
if(i < r_offset){
shape[i] = lhs[i];
}
else{
const int l = lhs[i];
const int r = rhs[i - r_offset];
if(l == r){
shape[i] = l; // no broadcast
} else if (l == 1){
shape[i] = r; // left broadcast
} else if (r == 1){
shape[i] = l; // right broadcast
} else{
std::stringstream ss;
ss << "Non operatable shapes ";
ss << "(" << lhs << " & " << rhs << ")";
throw std::runtime_error(ss.str());
}
}
}
return shape;
}
/**
* Return a new shape padded with extra dimensions of size 1
*/
static Shape PadShape(const Shape& shape, size_t size) {
if (size < shape.size()) {
throw std::runtime_error("Invalid shape to pad");
}
const size_t n_pad = size - shape.size();
Shape ret_shape;
ret_shape.reserve(size);
ret_shape.resize(n_pad, 1); // Fill by 1
ret_shape.insert(ret_shape.end(), shape.begin(), shape.end()); // Concat
return ret_shape;
}
/**
* Reduce the Shapes of tensors that are being operated on
*/
static size_t ReduceShapesBroadcast(Shape& ret_shape, Shape& l_shape,
Shape& r_shape, const size_t depth_offset) {
// Require `ret_shape.size() == l_shape.size() == r_shape.size()`
// Remove meaningless dimensions.
Shape ret_shape_cleaned, l_shape_cleaned, r_shape_cleaned;
int size_pool = 1;
size_t depth = 0;
for (; depth < ret_shape.size() - depth_offset; depth++) {
if (l_shape[depth] == r_shape[depth]) {
// Store
size_pool *= l_shape[depth];
} else {
// Pop
if (size_pool != 1) {
ret_shape_cleaned.push_back(size_pool);
l_shape_cleaned.push_back(size_pool);
r_shape_cleaned.push_back(size_pool);
size_pool = 1;
}
// Through current dimension
ret_shape_cleaned.push_back(ret_shape[depth]);
l_shape_cleaned.push_back(l_shape[depth]);
r_shape_cleaned.push_back(r_shape[depth]);
}
}
// Pop
if (size_pool != 1 || ret_shape_cleaned.size() == 0) {
ret_shape_cleaned.push_back(size_pool);
l_shape_cleaned.push_back(size_pool);
r_shape_cleaned.push_back(size_pool);
}
// Store actual depth count
const size_t n_depth = ret_shape_cleaned.size();
// Pass through included in `depth_offset`.
for (; depth < ret_shape.size(); depth++) {
ret_shape_cleaned.push_back(ret_shape[depth]);
l_shape_cleaned.push_back(l_shape[depth]);
r_shape_cleaned.push_back(r_shape[depth]);
}
// Return
ret_shape = std::move(ret_shape_cleaned);
l_shape = std::move(l_shape_cleaned);
r_shape = std::move(r_shape_cleaned);
return n_depth;
}
/**
* Size of each dimensions sub-dimensions
* shape = [3, 4, 2]
* child_sizes = [24, 8, 2]
*/
static std::vector<int> ComputeChildSizes(const Shape& shape) {
const size_t n_shape = shape.size();
if (n_shape == 0) {
return {};
}
// Compute child sizes from back (the number of children for each dimension)
std::vector<int> child_sizes(n_shape, 1);
int size = 1;
for (size_t depth = n_shape - 1; 0 < depth; depth--) {
child_sizes[depth] = size;
size *= shape[depth];
}
child_sizes[0] = size;
return child_sizes;
}
template <typename F>
void ApplyOpBroadcastImpl(float* ret_data,
const float* l_data,
const float* r_data,
const Shape& ret_shape, const int ret_size,
const std::vector<int>& l_steps,
const std::vector<int>& r_steps,
const size_t start_depth, const size_t n_depth,
const int ret_step, F op) {
// Create stacks and counter
std::vector<int> ret_cnts(n_depth);
std::vector<int> l_idx_stack(n_depth), r_idx_stack(n_depth);
size_t depth = start_depth;
int l_idx = 0;
int r_idx = 0;
for (int ret_idx = 0; ret_idx < ret_size; ret_idx += ret_step) {
// Go down
for (; depth < n_depth; depth++) {
l_idx_stack[depth] = l_idx; // Push stack
r_idx_stack[depth] = r_idx;
}
// Operate
op(ret_data + ret_idx, l_data + l_idx, r_data + r_idx);
// Go up and count
for (; start_depth < depth; depth--) {
const size_t prev_d = depth - 1;
ret_cnts[prev_d]++; // Count up
l_idx += l_steps[prev_d]; // Forward index
r_idx += r_steps[prev_d];
if (ret_cnts[prev_d] < ret_shape[prev_d]) {
break; // Continue normally
}
// Go upper depth
ret_cnts[prev_d] = 0; // Clear count
l_idx = l_idx_stack[prev_d]; // Pop stack
r_idx = r_idx_stack[prev_d];
}
}
}
/**
* Apply an operation to two tensors after broadcasting them to a matching shape
*/
template <typename F>
void ApplyOpBroadcast(Tensor& ret,
const Tensor& lhs,
const Tensor& rhs,
const size_t depth_offset,
const int ret_step,
F op){
Shape ret_shape = ret.shape();