-
Notifications
You must be signed in to change notification settings - Fork 10
/
tinyndarray.h
4313 lines (3710 loc) · 142 KB
/
tinyndarray.h
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
#ifndef TINYNDARRAY_H_ONCE
#define TINYNDARRAY_H_ONCE
#ifndef TINYNDARRAY_NO_INCLUDE
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cmath>
#include <exception>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <random>
#include <sstream>
#include <thread>
#include <vector>
#endif
#ifndef TINYNDARRAY_NO_NAMESPACE
namespace tinyndarray {
#endif // TINYNDARRAY_NO_NAMESPACE
// #############################################################################
// ############################ Begin of Declaration ###########################
// #############################################################################
#ifndef TINYNDARRAY_NO_DECLARATION
// Forward Declaration of TinyNdArray
class NdArray;
using InitShape = std::initializer_list<int>;
using Shape = std::vector<int>;
using Index = std::vector<int>;
using SliceIndex = std::vector<std::pair<int, int>>;
using Axis = std::vector<int>;
template <bool C>
using Float = std::conditional_t<C, const float, float>;
// =============================================================================
// ======================= Nested Float Initializer List =======================
// =============================================================================
template <std::size_t D>
struct FloatListHelper {
using type = std::initializer_list<typename FloatListHelper<D - 1>::type>;
};
template <>
struct FloatListHelper<0> {
using type = std::initializer_list<float>;
};
template <std::size_t D>
using FloatList = typename FloatListHelper<D>::type;
// =============================================================================
// ================================== NdArray ==================================
// =============================================================================
class NdArray {
public:
template <bool C>
class IterBase;
using Iter = IterBase<false>;
using ConstIter = IterBase<true>;
NdArray();
NdArray(const NdArray&);
NdArray(NdArray&&) noexcept;
NdArray& operator=(const NdArray&);
NdArray& operator=(NdArray&&);
~NdArray();
NdArray(FloatList<0> init_list);
NdArray(FloatList<1> init_list);
NdArray(FloatList<2> init_list);
NdArray(FloatList<3> init_list);
NdArray(FloatList<4> init_list);
NdArray(FloatList<5> init_list);
NdArray(FloatList<6> init_list);
NdArray(FloatList<7> init_list);
NdArray(FloatList<8> init_list);
NdArray(FloatList<9> init_list);
NdArray(const InitShape& shape);
NdArray(const Shape& shape);
NdArray(const Shape& shape, float fill_v);
static NdArray Empty(const Shape& shape);
static NdArray Zeros(const Shape& shape);
static NdArray Ones(const Shape& shape);
template <typename... S>
static NdArray Empty(S... shape);
template <typename... S>
static NdArray Zeros(S... shape);
template <typename... S>
static NdArray Ones(S... shape);
static NdArray Arange(float stop);
static NdArray Arange(float start, float stop, float step = 1.f);
static void Seed();
static void Seed(uint32_t seed);
static NdArray Uniform(float low = 0.f, float high = 1.f,
const Shape& shape = {1});
static NdArray Uniform(const Shape& shape);
static NdArray Normal(float loc = 0.f, float scale = 1.f,
const Shape& shape = {1});
static NdArray Normal(const Shape& shape);
static int GetNumWorkers();
static void SetNumWorkers(int n_workers); // -1: Hardware Concurrency
static int GetBatchScale();
static void SetBatchScale(int batch_scale);
// Profiling methods (Defining of `TINYNDARRAY_PROFILE_MEMORY` is needed)
static size_t GetNumInstance();
static size_t GetTotalMemory();
uintptr_t id() const;
bool empty() const;
size_t size() const;
const Shape& shape() const;
size_t ndim() const;
Iter data();
ConstIter data() const;
void fill(float v);
NdArray copy() const;
void resize(const Shape& shape);
Iter begin();
Iter end();
ConstIter begin() const;
ConstIter end() const;
operator float() const;
float& operator[](int i);
const float& operator[](int i) const;
float& operator[](const Index& index);
const float& operator[](const Index& index) const;
template <typename... I>
float& operator()(I... index);
template <typename... I>
const float& operator()(I... index) const;
NdArray reshape(const Shape& shape) const;
template <typename... S>
NdArray reshape(S... shape) const;
NdArray flatten() const; // with copy
NdArray ravel() const; // without copy
NdArray slice(const SliceIndex& slice_index) const;
template <typename... I>
NdArray slice(std::initializer_list<I>... slice_index) const; // {i, j}...
NdArray dot(const NdArray& other) const;
NdArray cross(const NdArray& other) const;
NdArray sum(const Axis& axes = {}, bool keepdims = false) const;
NdArray mean(const Axis& axes = {}, bool keepdims = false) const;
NdArray min(const Axis& axes = {}, bool keepdims = false) const;
NdArray max(const Axis& axes = {}, bool keepdims = false) const;
// Parameters
static constexpr int DOT_CACHE_SCALE = 10; // depends on situation and CPU
static constexpr int DEFAULT_N_WORKERS = -1;
static constexpr int DEFAULT_BATCH_SCALE = 4;
class Substance;
private:
std::shared_ptr<Substance> m_sub;
NdArray(std::shared_ptr<Substance> sub);
static std::random_device s_rand_seed;
static std::mt19937 s_rand_engine;
static int s_n_workers;
static int s_batch_scale;
};
// --------------------------------- Operators ---------------------------------
// Print
std::ostream& operator<<(std::ostream& os, const NdArray& x);
std::ostream& operator<<(std::ostream& os, const Shape& shape);
// Single
NdArray operator+(const NdArray& x);
NdArray operator-(const NdArray& x);
// Arithmetic (NdArray, NdArray)
NdArray operator+(const NdArray& lhs, const NdArray& rhs);
NdArray operator-(const NdArray& lhs, const NdArray& rhs);
NdArray operator*(const NdArray& lhs, const NdArray& rhs);
NdArray operator/(const NdArray& lhs, const NdArray& rhs);
// Arithmetic (NdArray, float)
NdArray operator+(const NdArray& lhs, float rhs);
NdArray operator-(const NdArray& lhs, float rhs);
NdArray operator*(const NdArray& lhs, float rhs);
NdArray operator/(const NdArray& lhs, float rhs);
// Arithmetic (float, NdArray)
NdArray operator+(float lhs, const NdArray& rhs);
NdArray operator-(float lhs, const NdArray& rhs);
NdArray operator*(float lhs, const NdArray& rhs);
NdArray operator/(float lhs, const NdArray& rhs);
// Comparison (NdArray, NdArray)
NdArray operator==(const NdArray& lhs, const NdArray& rhs);
NdArray operator!=(const NdArray& lhs, const NdArray& rhs);
NdArray operator>(const NdArray& lhs, const NdArray& rhs);
NdArray operator>=(const NdArray& lhs, const NdArray& rhs);
NdArray operator<(const NdArray& lhs, const NdArray& rhs);
NdArray operator<=(const NdArray& lhs, const NdArray& rhs);
// Comparison (NdArray, float)
NdArray operator==(const NdArray& lhs, float rhs);
NdArray operator!=(const NdArray& lhs, float rhs);
NdArray operator>(const NdArray& lhs, float rhs);
NdArray operator>=(const NdArray& lhs, float rhs);
NdArray operator<(const NdArray& lhs, float rhs);
NdArray operator<=(const NdArray& lhs, float rhs);
// Comparison (float, NdArray)
NdArray operator==(float lhs, const NdArray& rhs);
NdArray operator!=(float lhs, const NdArray& rhs);
NdArray operator>(float lhs, const NdArray& rhs);
NdArray operator>=(float lhs, const NdArray& rhs);
NdArray operator<(float lhs, const NdArray& rhs);
NdArray operator<=(float lhs, const NdArray& rhs);
// ----------------------------- In-place Operators ----------------------------
// Single
NdArray operator+(NdArray&& x);
NdArray operator-(NdArray&& x);
// Arithmetic (NdArray, NdArray)
NdArray operator+(NdArray&& lhs, NdArray&& rhs);
NdArray operator+(const NdArray& lhs, NdArray&& rhs);
NdArray operator+(NdArray&& lhs, const NdArray& rhs);
NdArray operator-(NdArray&& lhs, NdArray&& rhs);
NdArray operator-(const NdArray& lhs, NdArray&& rhs);
NdArray operator-(NdArray&& lhs, const NdArray& rhs);
NdArray operator*(NdArray&& lhs, NdArray&& rhs);
NdArray operator*(const NdArray& lhs, NdArray&& rhs);
NdArray operator*(NdArray&& lhs, const NdArray& rhs);
NdArray operator/(NdArray&& lhs, NdArray&& rhs);
NdArray operator/(const NdArray& lhs, NdArray&& rhs);
NdArray operator/(NdArray&& lhs, const NdArray& rhs);
// Arithmetic (NdArray, float)
NdArray operator+(NdArray&& lhs, float rhs);
NdArray operator-(NdArray&& lhs, float rhs);
NdArray operator*(NdArray&& lhs, float rhs);
NdArray operator/(NdArray&& lhs, float rhs);
// Arithmetic (float, NdArray)
NdArray operator+(float lhs, NdArray&& rhs);
NdArray operator-(float lhs, NdArray&& rhs);
NdArray operator*(float lhs, NdArray&& rhs);
NdArray operator/(float lhs, NdArray&& rhs);
// Comparison (NdArray, NdArray)
NdArray operator==(NdArray&& lhs, NdArray&& rhs);
NdArray operator==(const NdArray& lhs, NdArray&& rhs);
NdArray operator==(NdArray&& lhs, const NdArray& rhs);
NdArray operator!=(NdArray&& lhs, NdArray&& rhs);
NdArray operator!=(const NdArray& lhs, NdArray&& rhs);
NdArray operator!=(NdArray&& lhs, const NdArray& rhs);
NdArray operator>(NdArray&& lhs, NdArray&& rhs);
NdArray operator>(const NdArray& lhs, NdArray&& rhs);
NdArray operator>(NdArray&& lhs, const NdArray& rhs);
NdArray operator>=(NdArray&& lhs, NdArray&& rhs);
NdArray operator>=(const NdArray& lhs, NdArray&& rhs);
NdArray operator>=(NdArray&& lhs, const NdArray& rhs);
NdArray operator<(NdArray&& lhs, NdArray&& rhs);
NdArray operator<(const NdArray& lhs, NdArray&& rhs);
NdArray operator<(NdArray&& lhs, const NdArray& rhs);
NdArray operator<=(NdArray&& lhs, NdArray&& rhs);
NdArray operator<=(const NdArray& lhs, NdArray&& rhs);
NdArray operator<=(NdArray&& lhs, const NdArray& rhs);
// Comparison (NdArray, float)
NdArray operator==(NdArray&& lhs, float rhs);
NdArray operator!=(NdArray&& lhs, float rhs);
NdArray operator>(NdArray&& lhs, float rhs);
NdArray operator>=(NdArray&& lhs, float rhs);
NdArray operator<(NdArray&& lhs, float rhs);
NdArray operator<=(NdArray&& lhs, float rhs);
// Comparison (float, NdArray)
NdArray operator==(float lhs, NdArray&& rhs);
NdArray operator!=(float lhs, NdArray&& rhs);
NdArray operator>(float lhs, NdArray&& rhs);
NdArray operator>=(float lhs, NdArray&& rhs);
NdArray operator<(float lhs, NdArray&& rhs);
NdArray operator<=(float lhs, NdArray&& rhs);
// Compound Assignment (NdArray, NdArray)
NdArray operator+=(NdArray& lhs, const NdArray& rhs);
NdArray operator+=(NdArray&& lhs, const NdArray& rhs);
NdArray operator-=(NdArray& lhs, const NdArray& rhs);
NdArray operator-=(NdArray&& lhs, const NdArray& rhs);
NdArray operator*=(NdArray& lhs, const NdArray& rhs);
NdArray operator*=(NdArray&& lhs, const NdArray& rhs);
NdArray operator/=(NdArray& lhs, const NdArray& rhs);
NdArray operator/=(NdArray&& lhs, const NdArray& rhs);
// Compound Assignment (NdArray, float)
NdArray operator+=(NdArray& lhs, float rhs);
NdArray operator+=(NdArray&& lhs, float rhs);
NdArray operator-=(NdArray& lhs, float rhs);
NdArray operator-=(NdArray&& lhs, float rhs);
NdArray operator*=(NdArray& lhs, float rhs);
NdArray operator*=(NdArray&& lhs, float rhs);
NdArray operator/=(NdArray& lhs, float rhs);
NdArray operator/=(NdArray&& lhs, float rhs);
// ---------------------------- Operator Functions -----------------------------
// Single operators
NdArray Positive(const NdArray& lhs);
NdArray Negative(const NdArray& lhs);
// Arithmetic operators (NdArray, NdArray)
NdArray Add(const NdArray& lhs, const NdArray& rhs);
NdArray Subtract(const NdArray& lhs, const NdArray& rhs);
NdArray Multiply(const NdArray& lhs, const NdArray& rhs);
NdArray Divide(const NdArray& lhs, const NdArray& rhs);
// Arithmetic operators (NdArray, float)
NdArray Add(const NdArray& lhs, float rhs);
NdArray Subtract(const NdArray& lhs, float rhs);
NdArray Multiply(const NdArray& lhs, float rhs);
NdArray Divide(const NdArray& lhs, float rhs);
// Arithmetic operators (float, NdArray)
NdArray Add(float lhs, const NdArray& rhs);
NdArray Subtract(float lhs, const NdArray& rhs);
NdArray Multiply(float lhs, const NdArray& rhs);
NdArray Divide(float lhs, const NdArray& rhs);
// Comparison operators (NdArray, NdArray)
NdArray Equal(const NdArray& lhs, const NdArray& rhs);
NdArray NotEqual(const NdArray& lhs, const NdArray& rhs);
NdArray Greater(const NdArray& lhs, const NdArray& rhs); // >
NdArray GreaterEqual(const NdArray& lhs, const NdArray& rhs); // >=
NdArray Less(const NdArray& lhs, const NdArray& rhs); // <
NdArray LessEqual(const NdArray& lhs, const NdArray& rhs); // <=
// Comparison operators (NdArray, float)
NdArray Equal(const NdArray& lhs, float rhs);
NdArray NotEqual(const NdArray& lhs, float rhs);
NdArray Greater(const NdArray& lhs, float rhs);
NdArray GreaterEqual(const NdArray& lhs, float rhs);
NdArray Less(const NdArray& lhs, float rhs);
NdArray LessEqual(const NdArray& lhs, float rhs);
// Comparison operators (float, NdArray)
NdArray Equal(float lhs, const NdArray& rhs);
NdArray NotEqual(float lhs, const NdArray& rhs);
NdArray Greater(float lhs, const NdArray& rhs);
NdArray GreaterEqual(float lhs, const NdArray& rhs);
NdArray Less(float lhs, const NdArray& rhs);
NdArray LessEqual(float lhs, const NdArray& rhs);
// Matrix operators
NdArray Dot(const NdArray& lhs, const NdArray& rhs);
NdArray Matmul(const NdArray& lhs, const NdArray& rhs);
NdArray Cross(const NdArray& lhs, const NdArray& rhs);
// Basic math operators
NdArray Abs(const NdArray& x);
NdArray Sign(const NdArray& x);
NdArray Ceil(const NdArray& x);
NdArray Floor(const NdArray& x);
NdArray Clip(const NdArray& x, float x_min, float x_max);
NdArray Sqrt(const NdArray& x);
NdArray Exp(const NdArray& x);
NdArray Log(const NdArray& x);
NdArray Square(const NdArray& x);
NdArray Power(const NdArray& x, const NdArray& y);
NdArray Power(const NdArray& x, float y);
NdArray Power(float x, const NdArray& y);
// Trigonometric functions
NdArray Sin(const NdArray& x);
NdArray Cos(const NdArray& x);
NdArray Tan(const NdArray& x);
// Inverse trigonometric functions
NdArray ArcSin(const NdArray& x);
NdArray ArcCos(const NdArray& x);
NdArray ArcTan(const NdArray& x);
NdArray ArcTan2(const NdArray& y, const NdArray& x);
NdArray ArcTan2(const NdArray& y, float x);
NdArray ArcTan2(float y, const NdArray& x);
// Axis functions
NdArray Sum(const NdArray& x, const Axis& axes = {}, bool keepdims = false);
NdArray Mean(const NdArray& x, const Axis& axes = {}, bool keepdims = false);
NdArray Min(const NdArray& x, const Axis& axes = {}, bool keepdims = false);
NdArray Max(const NdArray& x, const Axis& axes = {}, bool keepdims = false);
// Logistic functions
bool All(const NdArray& x);
bool Any(const NdArray& x);
NdArray All(const NdArray& x, const Axis& axes, bool keepdims = false);
NdArray Any(const NdArray& x, const Axis& axes, bool keepdims = false);
NdArray Where(const NdArray& cond, const NdArray& x, const NdArray& y);
NdArray Where(const NdArray& cond, const NdArray& x, float y);
NdArray Where(const NdArray& cond, float x, const NdArray& y);
NdArray Where(const NdArray& cond, float x, float y);
// Shape functions
NdArray Reshape(const NdArray& x, const Shape& shape);
NdArray Squeeze(const NdArray& x, const Axis& axes = {});
NdArray ExpandDims(const NdArray& x, int axis);
// Grouping functions
NdArray Stack(const std::vector<NdArray>& xs, int axis = 0);
NdArray Concatenate(const std::vector<NdArray>& xs, int axis = 0);
std::vector<NdArray> Split(const NdArray& x, int n_section, int axis = 0);
std::vector<NdArray> Split(const NdArray& x, const Index& idxs, int axis = 0);
std::vector<NdArray> Separate(const NdArray& x, int axis = 0);
// Change view
NdArray Transpose(const NdArray& x);
NdArray Swapaxes(const NdArray& x, int axis1, int axis2);
NdArray BroadcastTo(const NdArray& x, const Shape& shape);
NdArray SumTo(const NdArray& x, const Shape& shape);
// Inverse
NdArray Inv(const NdArray& x);
// ------------------------ In-place Operator Functions ------------------------
// Single operators
NdArray Positive(NdArray&& lhs);
NdArray Negative(NdArray&& lhs);
// Arithmetic operators (NdArray, NdArray)
NdArray Add(NdArray&& lhs, NdArray&& rhs);
NdArray Add(const NdArray& lhs, NdArray&& rhs);
NdArray Add(NdArray&& lhs, const NdArray& rhs);
NdArray Subtract(NdArray&& lhs, NdArray&& rhs);
NdArray Subtract(const NdArray& lhs, NdArray&& rhs);
NdArray Subtract(NdArray&& lhs, const NdArray& rhs);
NdArray Multiply(NdArray&& lhs, NdArray&& rhs);
NdArray Multiply(const NdArray& lhs, NdArray&& rhs);
NdArray Multiply(NdArray&& lhs, const NdArray& rhs);
NdArray Divide(NdArray&& lhs, NdArray&& rhs);
NdArray Divide(const NdArray& lhs, NdArray&& rhs);
NdArray Divide(NdArray&& lhs, const NdArray& rhs);
// Arithmetic operators (NdArray, float)
NdArray Add(NdArray&& lhs, float rhs);
NdArray Subtract(NdArray&& lhs, float rhs);
NdArray Multiply(NdArray&& lhs, float rhs);
NdArray Divide(NdArray&& lhs, float rhs);
// Arithmetic operators (float, NdArray)
NdArray Add(float lhs, NdArray&& rhs);
NdArray Subtract(float lhs, NdArray&& rhs);
NdArray Multiply(float lhs, NdArray&& rhs);
NdArray Divide(float lhs, NdArray&& rhs);
// Comparison operators (NdArray, NdArray)
NdArray Equal(NdArray&& lhs, NdArray&& rhs);
NdArray Equal(const NdArray& lhs, NdArray&& rhs);
NdArray Equal(NdArray&& lhs, const NdArray& rhs);
NdArray NotEqual(NdArray&& lhs, NdArray&& rhs);
NdArray NotEqual(const NdArray& lhs, NdArray&& rhs);
NdArray NotEqual(NdArray&& lhs, const NdArray& rhs);
NdArray Greater(NdArray&& lhs, NdArray&& rhs);
NdArray Greater(const NdArray& lhs, NdArray&& rhs);
NdArray Greater(NdArray&& lhs, const NdArray& rhs);
NdArray GreaterEqual(NdArray&& lhs, NdArray&& rhs);
NdArray GreaterEqual(const NdArray& lhs, NdArray&& rhs);
NdArray GreaterEqual(NdArray&& lhs, const NdArray& rhs);
NdArray Less(NdArray&& lhs, NdArray&& rhs);
NdArray Less(const NdArray& lhs, NdArray&& rhs);
NdArray Less(NdArray&& lhs, const NdArray& rhs);
NdArray LessEqual(NdArray&& lhs, NdArray&& rhs);
NdArray LessEqual(const NdArray& lhs, NdArray&& rhs);
NdArray LessEqual(NdArray&& lhs, const NdArray& rhs);
// Comparison operators (NdArray, float)
NdArray Equal(NdArray&& lhs, float rhs);
NdArray NotEqual(NdArray&& lhs, float rhs);
NdArray Greater(NdArray&& lhs, float rhs);
NdArray GreaterEqual(NdArray&& lhs, float rhs);
NdArray Less(NdArray&& lhs, float rhs);
NdArray LessEqual(NdArray&& lhs, float rhs);
// Comparison operators (float, NdArray)
NdArray Equal(float lhs, NdArray&& rhs);
NdArray NotEqual(float lhs, NdArray&& rhs);
NdArray Greater(float lhs, NdArray&& rhs);
NdArray GreaterEqual(float lhs, NdArray&& rhs);
NdArray Less(float lhs, NdArray&& rhs);
NdArray LessEqual(float lhs, NdArray&& rhs);
// Basic math operators
NdArray Abs(NdArray&& x);
NdArray Sign(NdArray&& x);
NdArray Ceil(NdArray&& x);
NdArray Floor(NdArray&& x);
NdArray Clip(NdArray&& x, float x_min, float x_max);
NdArray Sqrt(NdArray&& x);
NdArray Exp(NdArray&& x);
NdArray Log(NdArray&& x);
NdArray Square(NdArray&& x);
NdArray Power(NdArray&& x, NdArray&& y);
NdArray Power(const NdArray& x, NdArray&& y);
NdArray Power(NdArray&& x, const NdArray& y);
NdArray Power(NdArray&& x, float y);
NdArray Power(float x, NdArray&& y);
// Trigonometric functions
NdArray Sin(NdArray&& x);
NdArray Cos(NdArray&& x);
NdArray Tan(NdArray&& x);
// Inverse trigonometric functions
NdArray ArcSin(NdArray&& x);
NdArray ArcCos(NdArray&& x);
NdArray ArcTan(NdArray&& x);
NdArray ArcTan2(NdArray&& y, NdArray&& x);
NdArray ArcTan2(const NdArray& y, NdArray&& x);
NdArray ArcTan2(NdArray&& y, const NdArray& x);
NdArray ArcTan2(NdArray&& y, float x);
NdArray ArcTan2(float y, NdArray&& x);
// Logistic functions
NdArray Where(NdArray&& cond, const NdArray& x, const NdArray& y);
NdArray Where(NdArray&& cond, const NdArray& x, float y);
NdArray Where(NdArray&& cond, float x, const NdArray& y);
NdArray Where(NdArray&& cond, float x, float y);
// Inverse
NdArray Inv(NdArray&& x);
// --------------------------------- Iterator ----------------------------------
template <bool C>
class NdArray::IterBase {
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = Float<C>;
using difference_type = std::ptrdiff_t;
using pointer = Float<C>*;
using reference = Float<C>&;
IterBase(Float<C>* p_);
virtual ~IterBase();
Float<C>& operator*() const;
Float<C>& operator[](int i) const;
IterBase& operator++();
IterBase& operator--();
IterBase operator++(int);
IterBase operator--(int);
IterBase operator+(int i) const;
IterBase operator-(int i) const;
IterBase& operator+=(int i);
IterBase& operator-=(int i);
bool operator==(const IterBase& other) const;
bool operator!=(const IterBase& other) const;
operator ConstIter() const;
private:
Float<C>* p;
};
// --------------------- Iterator Template Implementation ----------------------
template <bool C>
NdArray::IterBase<C>::IterBase(Float<C>* p_) : p(p_) {}
template <bool C>
NdArray::IterBase<C>::~IterBase() {}
template <bool C>
Float<C>& NdArray::IterBase<C>::operator*() const {
return *p;
}
template <bool C>
Float<C>& NdArray::IterBase<C>::operator[](int i) const {
return p[i];
}
template <bool C>
NdArray::IterBase<C>& NdArray::IterBase<C>::operator++() {
p++;
return *this;
}
template <bool C>
NdArray::IterBase<C>& NdArray::IterBase<C>::operator--() {
p--;
return *this;
}
template <bool C>
NdArray::IterBase<C> NdArray::IterBase<C>::operator++(int) {
IterBase tmp = *this;
p++;
return tmp;
}
template <bool C>
NdArray::IterBase<C> NdArray::IterBase<C>::operator--(int) {
IterBase tmp = *this;
p--;
return tmp;
}
template <bool C>
NdArray::IterBase<C> NdArray::IterBase<C>::operator+(int i) const {
return {p + i};
}
template <bool C>
NdArray::IterBase<C> NdArray::IterBase<C>::operator-(int i) const {
return {p - i};
}
template <bool C>
NdArray::IterBase<C>& NdArray::IterBase<C>::operator+=(int i) {
p += i;
return *this;
}
template <bool C>
NdArray::IterBase<C>& NdArray::IterBase<C>::operator-=(int i) {
p -= i;
return *this;
}
template <bool C>
bool NdArray::IterBase<C>::operator==(const IterBase& other) const {
return p == other.p;
}
template <bool C>
bool NdArray::IterBase<C>::operator!=(const IterBase& other) const {
return p != other.p;
}
template <bool C>
NdArray::IterBase<C>::operator NdArray::ConstIter() const {
return NdArray::ConstIter{p};
}
#endif // TINYNDARRAY_NO_DECLARATION
// #############################################################################
// ############################# End of Declaration ############################
// #############################################################################
// #############################################################################
// ############################ Begin of Definitions ###########################
// #############################################################################
#ifdef TINYNDARRAY_IMPLEMENTATION
// -----------------------------------------------------------------------------
// --------------------------- Utilities for NdArray ---------------------------
// -----------------------------------------------------------------------------
inline float SignOp(float x) {
if (0.f < x) {
return 1.f;
} else if (x < 0.f) {
return -1.f;
} else {
return 0.f;
}
}
inline float SquareOp(float x) {
return x * x;
}
template <typename T>
inline T ClipOp(const T& v, const T& lower, const T& upper) {
return std::min(std::max(v, lower), upper);
}
template <typename F>
inline auto ReverseOp(F op) {
return [op](float a, float b) { return op(b, a); }; // Swap left and right
}
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 void GetParallelParams(int size, int& n_workers, int& n_batch,
int& batch_size) {
// Fetch the number of workers
n_workers = NdArray::GetNumWorkers();
if (n_workers <= 0) {
n_workers = static_cast<int>(std::thread::hardware_concurrency());
}
// Compute batch size and it number
n_batch = n_workers * NdArray::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);
}
}
template <typename Iter>
void FillN(Iter&& iter, const int n, float v) {
// Fill in parallel
RunParallel(n, [&](int i) { iter[i] = v; });
}
template <typename RetIter, typename SrcIter>
void Copy(RetIter&& ret_iter, SrcIter&& src_iter, const int n) {
// Copy in parallel
RunParallel(n, [&](int i) { ret_iter[i] = src_iter[i]; });
}
template <typename F>
inline void ApplyOpSimple(NdArray& ret, F op) {
auto&& ret_data = ret.data();
// Simply apply all
RunParallel(static_cast<int>(ret.size()),
[&](int i) { ret_data[i] = op(); });
}
template <typename F>
inline void ApplyOpSimple(NdArray& ret, const NdArray& src, F op) {
auto&& ret_data = ret.data();
auto&& src_data = src.data();
// Simply apply all
RunParallel(static_cast<int>(ret.size()),
[&](int i) { ret_data[i] = op(src_data[i]); });
}
template <typename F>
inline void ApplyOpSimple(NdArray& ret, const NdArray& lhs, const NdArray& rhs,
F op) {
auto&& ret_data = ret.data();
auto&& l_data = lhs.data();
auto&& r_data = rhs.data();
// Simply apply all
RunParallel(static_cast<int>(ret.size()),
[&](int i) { ret_data[i] = op(l_data[i], r_data[i]); });
}
template <typename F>
inline void ApplyOpSimple(NdArray& ret, const NdArray& lhs, const float rhs,
F op) {
auto&& ret_data = ret.data();
auto&& l_data = lhs.data();
// Simply apply all
RunParallel(static_cast<int>(ret.size()),
[&](int i) { ret_data[i] = op(l_data[i], rhs); });
}
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;
}
// --------------- Utilities for NdArray (Float initializer list) --------------
template <typename FList>
std::list<int> CheckFListShapeImpl(const FList& init_list) {
if (init_list.size() == 0) {
return {};
}
// Check all children have same shape
auto itr = init_list.begin();
auto shape = CheckFListShapeImpl(*itr);
for (size_t i = 0; i < init_list.size(); i++, itr++) {
if (shape != CheckFListShapeImpl(*itr)) {
throw std::runtime_error("Initializing shape is invalid");
}
}
// Return total shape of children
shape.push_front(static_cast<int>(init_list.size()));
return shape;
}
template <>
inline std::list<int> CheckFListShapeImpl(const FloatList<0>& init_list) {
return {static_cast<int>(init_list.size())};
}
template <typename FList>
Shape CheckFListShape(const FList& init_list) {
// Check and get the shape of nested initializer.
const std::list<int>& shape = CheckFListShapeImpl(init_list);
// Cast to vector
return Shape(shape.begin(), shape.end());
}
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);
}
}
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) {
// Pass to impl (create pointer instance)
CopyFListElemsImpl(init_list, data);
}
// ---------------------- Utilities for NdArray (Random) -----------------------
template <typename D, typename R>
NdArray CreateRandomArray(const Shape& shape, D&& dist, R&& rand_engine) {
// Create empty array
NdArray ret(shape);
// Fill by random value
ApplyOpSimple(ret, [&]() { return static_cast<float>(dist(rand_engine)); });
return ret;
}
// ----------------------- Utilities for NdArray (Slice) -----------------------
static void CopySliceImpl(const NdArray::ConstIter& src_data,
const NdArray::Iter& ret_data, const Shape& ret_shape,
const std::vector<int>& prev_offsets,
const std::vector<int>& post_offsets,
const int src_step_top, const int ret_step_top) {
const size_t n_depth = ret_shape.size();
// Run in parallel (Only top level)
RunParallel(ret_shape[0], [&](int ret_top) {
const int ret_idx_base = ret_top * ret_step_top;
const int src_idx_base = ret_top * src_step_top + prev_offsets[0];
// Create stacks and counter
std::vector<int> ret_cnts(n_depth);
size_t depth = 1; // Start from 1
int src_idx = 0;
for (int ret_idx = 0; ret_idx < ret_step_top; ret_idx++) {
// Go down
for (; depth < n_depth; depth++) {
src_idx += prev_offsets[depth]; // Forward prev offset
}
// Operate
ret_data[ret_idx_base + ret_idx] = src_data[src_idx_base + src_idx];
src_idx += 1; // Forward normally
// Go up and count (Down to 1)
for (; 1 < depth; depth--) {
const size_t prev_d = depth - 1;
ret_cnts[prev_d]++; // Count up
if (ret_cnts[prev_d] < ret_shape[prev_d]) {
break; // Continue normally
}
// Go upper depth
ret_cnts[prev_d] = 0; // Clear count
src_idx += post_offsets[prev_d]; // Forward post offset
}
}
});
}
template <bool IsPrev>
std::vector<int> ComputeSliceOffset(const std::vector<int>& child_sizes,
const SliceIndex& slice_index,
const Shape& src_shape) {
std::vector<int> offsets;
offsets.reserve(child_sizes.size());
for (size_t depth = 0; depth < child_sizes.size(); depth++) {
const auto& si = slice_index[depth];
const int len = (IsPrev ? si.first : src_shape[depth] - si.second);
offsets.push_back(child_sizes[depth] * len);
}
return offsets;
}
static NdArray CopySlice(const NdArray& src, const Shape& ret_shape,
const SliceIndex& slice_index) {
const Shape& src_shape = src.shape();
// Pre-compute child sizes
const std::vector<int>& child_sizes = ComputeChildSizes(src_shape);
// Pre-compute offsets
const std::vector<int>& prev_offsets =
ComputeSliceOffset<true>(child_sizes, slice_index, src_shape);
const std::vector<int>& post_offsets =
ComputeSliceOffset<false>(child_sizes, slice_index, src_shape);
// Pre-compute top steps for parallel
const int ret_step_top = std::accumulate(
ret_shape.begin() + 1, ret_shape.end(), 1, std::multiplies<int>());
const int src_step_top = child_sizes[0];
// Create slice instance
NdArray ret(ret_shape);
// Start to copy
auto&& src_data = src.data();
auto&& ret_data = ret.data();
CopySliceImpl(src_data, ret_data, ret_shape, prev_offsets, post_offsets,
src_step_top, ret_step_top);
return ret;
}
inline std::pair<int, int> CvtToSliceIndexItem(std::initializer_list<int> l) {
if (l.size() != 2) {
throw std::runtime_error("Invalid slice index format");
}
return {*l.begin(), *(l.begin() + 1)};
}