-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
3718 lines (3157 loc) · 130 KB
/
main.cpp
File metadata and controls
3718 lines (3157 loc) · 130 KB
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 <iostream>
#include <chrono>
#include <stack>
#include <vector>
#include <array>
#include <cmath>
#include <random>
#include <iomanip>
#include <limits>
#include <cassert>
#include <utility>
#include <functional>
#include <fstream>
#define COMPETITION
#ifndef COMPETITION
//#define COLOR_BOARD
#define USE_THREADS
#define INCLUDE_FILE_SYSTEM
#endif
#ifdef INCLUDE_FILE_SYSTEM
#include <filesystem>
#endif
#ifdef USE_THREADS
#include <thread>
#endif
typedef uint_fast8_t uint8;
typedef unsigned int uint;
template <typename T>
using vector_stack = std::stack<T, std::vector<T>>;
#define nd_c [[nodiscard]] constexpr
inline std::ostream &operator<<(std::ostream &out, unsigned char c) {
return out << (int)c;
}
namespace Utils {
template <typename T>
constexpr T ceilDivide(T a, T b) {
return 1 + ((a - 1) / b);
}
template <typename OUT=char, typename IN>
constexpr static inline OUT* r_cast(IN &in) {
return reinterpret_cast<OUT*>(&in);
}
template <typename OUT=char, typename IN>
constexpr static inline const OUT* r_cast_const(const IN &in) {
return reinterpret_cast<const OUT*>(&in);
}
template <typename... Ts>
void swapEndian(Ts&... args) {
((args = (args>>24) |
((args<<8) & 0x00FF0000) |
((args>>8) & 0x0000FF00) |
(args<<24)), ...);
}
template <typename T>
constexpr T* initializeArray(std::initializer_list<T> init) {
auto r = new T[init.size()];
std::copy(init.begin(), init.end(), r);
return r;
}
template <typename T>
constexpr void printHardCodeArray(const T* arr, uint len, std::ostream &out, const std::string &type="T") {
out << "Utils::initializeArray<"<<type<<">({";
for (uint i = 0; i < len; ++i) {
out << (float)arr[i] << ',';
}
out << "})" << std::defaultfloat;
}
struct Random;
static Random* RNG{};
static std::mt19937* RNG2{};
struct Random final {
uint seed;
explicit Random(
const uint64_t &seed=
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count()
): seed(seed) {}
[[nodiscard]]
inline uint nextInt() {
seed = (214013u * seed + 2531011u);
return (seed >> 16u) & 0x7FFFu;
}
[[nodiscard]]
inline uint nextInt(uint range) {
return nextInt() % range;
}
[[nodiscard]]
inline bool nextBoolean() {
return nextInt() & 1u;
}
inline friend std::ostream &operator<<(std::ostream &out, const Random &rand) {
out << rand.seed;
return out;
}
static inline void init() {
RNG = new Random();
std::cerr << *RNG << '\n';
auto seed2 = std::random_device()();
std::cerr << seed2 << '\n';
RNG2 = new std::mt19937(seed2);
}
};
class BitSet64 {
public:
uint64_t word = 0;
constexpr BitSet64() = default;
constexpr BitSet64(uint64_t word): word(word) {}
nd_c bool get(uint index) const {
return (1ull << index) & word;
}
constexpr BitSet64& orSet(uint index) {
word |= (1ull << index);
return *this;
}
constexpr void unset(uint index) {
word &= ~(1ull << index);
}
nd_c uint count() const {
return __builtin_popcountll(word);
}
constexpr BitSet64 operator|(const BitSet64 &o) const {
return word | o.word;
}
constexpr BitSet64 operator&(const BitSet64 &o) const {
return word & o.word;
}
constexpr explicit operator bool() const {
return word;
}
constexpr BitSet64 &operator|=(const BitSet64 &o) {
word |= o.word;
return *this;
}
constexpr BitSet64 &operator<<=(uint x) {
word <<= x;
return *this;
}
constexpr BitSet64 &operator>>=(uint x) {
word >>= x;
return *this;
}
nd_c BitSet64 operator^(const BitSet64 &o) const {
return word ^ o.word;
}
template <typename T>
nd_c T sub(uint pos, uint count) const {
return (T)((word >> pos) & ((1ull << count) - 1ull));
}
struct iterator {
using iterator_category = std::forward_iterator_tag;
using value_type = uint;
uint64_t a = 0;
constexpr void operator++() {
a ^= -a & a;
}
constexpr uint operator*() const {
return __builtin_ctzll(a);
}
constexpr bool operator!=(const iterator &o) const {
return a != o.a;
}
};
nd_c iterator begin() const {
return {word};
}
nd_c iterator end() const {
return {0};
}
};
template <uint N>
class TwoBitArray {
public:
BitSet64 _words[ceilDivide(N << 1, 64u)];
public:
constexpr TwoBitArray() = default;
nd_c uint get(uint index) const {
return _words[index / 32].template sub<uint>(index % 32 * 2, 2);
}
constexpr void orSet(uint index, uint v) {
_words[index / 32].word |= ((uint64_t)v << (index % 32 * 2));
}
constexpr void unset(uint index) {
_words[index / 32].word &= ~(3ull << (index % 32 * 2));
}
constexpr void set(uint index, uint v) {
unset(index);
if (v) orSet(index, v);
}
};
}
namespace Utils::Math {
typedef double floating_type;
typedef uint32_t size_type;
struct Shape2D {
size_type height=1, width=1;
nd_c size_type area() const {
return height * width;
}
friend std::ostream &operator<<(std::ostream &out, const Shape2D &shape) {
return out << "{" + std::to_string(shape.height) + ", " + std::to_string(shape.width) + "}";
}
};
struct Shape3D {
size_type height=1, width=1, depth=1;
constexpr size_type volume() const {
return height * width * depth;
}
friend std::ostream &operator<<(std::ostream &out, const Shape3D &shape) {
return out << "{" + std::to_string(shape.height) + ", " + std::to_string(shape.width) + ", " + std::to_string(shape.depth) + "}";
}
};
namespace Matrix {
template <
typename MAT_P,
typename T_P = typename MAT_P::value_type,
typename MAT_A,
typename MAT_B
>
constexpr static MAT_P &dotReference(
const MAT_A &A,
const MAT_B &B,
MAT_P &product
) {
for (size_type j = 0; j < B.columns(); ++j) {
for (size_type i = 0; i < A.rows(); ++i) {
product(i, j) = T_P();
for (size_type index = 0; index < A.columns(); ++index) {
product(i, j) += (T_P)(A(i, index) * B(index, j));
}
}
}
return product;
}
template <
typename MAT_P,
typename Function1,
typename Function2,
typename T_P = typename MAT_P::value_type,
typename MAT_A,
typename MAT_B
>
constexpr static void dotIteration(
const MAT_A &A,
const MAT_B &B,
MAT_P* product,
Function1 f1,
Function2 f2
) {
for (size_type j = 0; j < B.columns(); ++j) {
for (size_type i = 0; i < A.rows(); ++i) {
T_P t = T_P();
for (size_type index = 0; index < A.columns(); ++index) {
f1(i, j, index);
t += static_cast<T_P>(A(i, index) * B(index, j));
}
f2(t, i, j);
if (product) (*product)(i, j) = t;
}
}
}
template <
typename MAT_P,
typename T_P = typename MAT_P::value_type,
typename... Args,
typename MAT_A,
typename MAT_B
>
constexpr static MAT_P dot(
const MAT_A &A,
const MAT_B &B,
Args&&... args
) {
MAT_P product(std::forward<Args>(args)...);
dotReference<MAT_P, T_P>(A, B, product);
return product;
}
template <
typename MAT_S,
typename T_P = typename MAT_S::value_type,
typename MAT_A,
typename MAT_B
>
constexpr static MAT_S &addReference(
const MAT_A &A,
const MAT_B &B,
MAT_S &sum
) {
for (size_type i = 0; i < A.rows(); ++i) for (size_type j = 0; j < A.columns(); ++j)
sum(i, j) = static_cast<T_P>(A(i, j) + B(i, j));
return sum;
}
template <
typename MAT_S,
typename T_P = typename MAT_S::value_type,
typename... Args,
typename MAT_A,
typename MAT_B
>
constexpr static MAT_S add(
const MAT_A &A,
const MAT_B &B,
Args&&... args
) {
MAT_S sum(std::forward<Args>(args)...);
addReference<MAT_S, T_P>(A, B, sum);
return sum;
}
template <
typename MAT_R,
typename T_P = typename MAT_R::value_type,
typename MAT_A,
typename MAT_B
>
constexpr static void convolve(
const MAT_A &A,
const MAT_B &kernel,
MAT_R &result
) {
for (size_type ki = 0; ki < kernel.rows(); ++ki) {
for (size_type kj = 0; kj < kernel.columns(); ++kj) {
auto kij = kernel(ki, kj);
if (!kij) continue;
for (size_type i = 0; i < result.rows(); ++i) { // stride with i += stride
for (size_type j = 0; j < result.columns(); ++j) {
result(i, j) += static_cast<T_P>(A(i+ki, j+kj) * kij);
}
}
}
}
}
template <typename MAT, typename T_M = typename MAT::value_type>
constexpr static void fill(MAT &matrix, const T_M &a) {
for (size_type i = 0; i < matrix.rows(); ++i) {
for (size_type j = 0; j < matrix.columns(); ++j) {
matrix(i, j) = a;
}
}
}
template <typename R, typename MAT, typename... Args>
constexpr static void copy(const MAT &m, Args&&... args) {
R result(std::forward<Args>(args)...);
for (size_type i = 0; i < m.rows(); ++i) {
for (size_type j = 0; j < m.columns(); ++j) {
result(i, j) = m(i, j);
}
}
return result;
}
template <typename MAT>
std::ostream &print(const MAT &matrix, std::ostream &out=std::cout) {
out << '{';
for (size_type i = 0; i < matrix.rows(); ++i) {
if (i) out << ' ';
out << '{';
for (size_type j = 0; j < matrix.columns(); ++j) {
out << (j? ',': ' ') << " " << matrix(i, j);
}
out << '}' << (i+1 == matrix.rows()? '}': '\n');
}
return out << '\n';
}
template <typename MAT> class TransposedMatrixReference;
template <typename MAT>
class TransposedMatrixReference {
public:
typedef MAT Matrix;
typedef typename Matrix::value_type value_type;
protected:
Matrix &ref;
public:
constexpr explicit TransposedMatrixReference(Matrix &matrix): ref(matrix) {
}
// Start Matrix Functions
[[nodiscard]]
constexpr size_type rows() const noexcept {
return ref.columns();
}
[[nodiscard]]
constexpr size_type columns() const noexcept {
return ref.rows();
}
// Start Operators
[[nodiscard]]
constexpr value_type &operator()(size_type i, size_type j) {
return ref(j, i);
}
[[nodiscard]]
constexpr const value_type &operator()(size_type i, size_type j) const {
return ref(j, i);
}
// End Operators
// End Matrix Functions
};
template <typename MAT>
class PaddedMatrixReference {
public:
typedef MAT Matrix;
typedef typename Matrix::value_type value_type;
protected:
const Matrix &ref;
const size_type padding;
const value_type padding_fill;
public:
constexpr PaddedMatrixReference(const Matrix &matrix, size_type padding, value_type paddingFill=0):
ref(matrix), padding(padding), padding_fill(paddingFill)
{}
// Start Matrix Functions
[[nodiscard]]
constexpr size_type rows() const noexcept {
return ref.rows() + (padding << 1);
}
[[nodiscard]]
constexpr size_type columns() const noexcept {
return ref.columns() + (padding << 1);
}
// Start Operators
[[nodiscard]]
constexpr const value_type &operator()(size_type i, size_type j) const {
if (i-padding < ref.rows() && j-padding < ref.columns()) return ref(i-padding, j-padding);
return padding_fill;
}
// End Operators
// End Matrix Functions
};
template <typename T = floating_type>
class DynamicMatrix {
public:
typedef T value_type;
size_type m = 0, n = 0;
value_type* array = nullptr;
// Start Constructors
constexpr DynamicMatrix() = default;
template <typename InputIt>
constexpr DynamicMatrix(InputIt first, InputIt last, size_type rows):
m(rows),
n(std::distance(first, last) / rows),
array(new value_type[std::distance(first, last)]) {
std::copy(first, last, array);
}
constexpr explicit DynamicMatrix(size_type rows, size_type columns):
m(rows),
n(columns),
array(new value_type[rows * columns]) {
}
constexpr DynamicMatrix(const DynamicMatrix &o): DynamicMatrix(
o.array,
o.array + o.m * o.n,
o.m) {
//std::cerr << "copied matrix\n";
}
constexpr DynamicMatrix(DynamicMatrix &&o) noexcept: m(std::move(o.m)), n(std::move(o.n)), array(o.array) {
o.array = nullptr;
}
constexpr DynamicMatrix(std::initializer_list<std::initializer_list<value_type>> l):
m(l.size()), n(l.begin()->size())
{
array = new value_type[m * n];
for (size_type i = 0; i < l.size(); ++i) {
const auto &itl = l.begin() + i;
assert(("All rows must be equal sized.", itl->size() == n));
std::copy<typename std::initializer_list<value_type>::const_iterator, value_type*>(
itl->begin(), itl->end(), array + i * n
);
}
std::cout << "created matrix " << this << '\n';
}
constexpr DynamicMatrix(value_type* arr, size_type m, size_type n): m(m), n(n), array(arr) {
}
// End Constructors
constexpr DynamicMatrix &operator=(const DynamicMatrix &o) noexcept {
std::cout << "copied matrix\n";
delete[] array;
m = o.m;
n = o.n;
array = new value_type[m * n];
std::copy(o.array, o.array + m * n, array);
//std::cout << "copied matrix " << &o << " to " << this << "\n";
return *this;
}
constexpr DynamicMatrix &operator=(DynamicMatrix &&o) noexcept {
// std::cout << "moved matrix\n";
delete[] array;
m = o.m;
n = o.n;
array = o.array;
o.array = nullptr;
return *this;
}
public:
~DynamicMatrix() {
delete[] array;
}
// Start Matrix Functions
[[nodiscard]]
constexpr size_type rows() const noexcept {
return m;
}
[[nodiscard]]
constexpr size_type columns() const noexcept {
return n;
}
// Start Operators
[[nodiscard]]
constexpr value_type &operator()(size_type i, size_type j) {
return array[i * n + j];
}
[[nodiscard]]
constexpr const value_type &operator()(size_type i, size_type j) const {
return array[i * n + j];
}
// End Operators
// End Matrix Functions
template <
typename T_O = value_type,
typename T_R=T_O
>
constexpr DynamicMatrix<T_R> operator*(const DynamicMatrix<T_O> &other) const {
return dot<DynamicMatrix<T_R>, T_R>(*this, other, m, other.n);
}
inline friend std::ostream &operator<<(std::ostream &out, const DynamicMatrix &matrix) {
return print(matrix);
}
};
template <typename T = floating_type, bool IS_COLUMN_VECTOR=true>
class DynamicVector {
public:
typedef T value_type;
static constexpr const bool vector_type = IS_COLUMN_VECTOR;
size_type n = 0;
value_type* array = nullptr;
// Start Constructors
constexpr DynamicVector() = default;
template <typename InputIt>
constexpr DynamicVector(InputIt first, InputIt last):
n(std::distance(first, last)),
array(new value_type[std::distance(first, last)]) {
std::copy(first, last, array);
}
constexpr explicit DynamicVector(size_type _n):
n(_n),
array(new value_type[_n]) {
}
constexpr DynamicVector(const DynamicVector &o): DynamicVector(o.array, o.array + o.n) {
std::cerr << "copied vector\n";
}
constexpr DynamicVector(DynamicVector &&o) noexcept: n(std::move(o.n)), array(o.array) {
o.array = nullptr;
}
constexpr DynamicVector(std::initializer_list<value_type> l):
DynamicVector(l.begin(), l.end()) {
}
constexpr DynamicVector(value_type* arr, size_type n): n(n), array(arr) {
}
// End Constructors
constexpr DynamicVector &operator=(const DynamicVector &o) noexcept {
std::cout << "copied vector\n";
delete[] array;
n = o.n;
array = new value_type[n];
std::copy(o.array, o.array + n, array);
return *this;
}
constexpr DynamicVector &operator=(DynamicVector &&o) noexcept {
//std::cout << "moved vector\n";
delete[] array;
n = o.n;
array = o.array;
o.array = nullptr;
return *this;
}
public:
~DynamicVector() {
delete[] array;
}
// Start Matrix Functions
[[nodiscard]]
constexpr size_type rows() const noexcept {
return vector_type? n: 1;
}
[[nodiscard]]
constexpr size_type columns() const noexcept {
return vector_type? 1: n;
}
// Start Operators
[[nodiscard]]
constexpr value_type &operator()(size_type i, size_type j) {
return array[i + j];
}
[[nodiscard]]
constexpr const value_type &operator()(size_type i, size_type j) const {
return array[i + j];
}
// End Operators
// End Matrix Functions
[[nodiscard]]
constexpr value_type &operator[](size_type i) {
return array[i];
}
[[nodiscard]]
constexpr const value_type &operator[](size_type i) const {
return array[i];
}
inline friend std::ostream &operator<<(std::ostream &out, const DynamicVector &matrix) {
return print(matrix, out);
}
};
}
template <typename T>
Matrix::DynamicVector<T> dirichlet(T alpha, uint size, std::mt19937 &gen) {
Matrix::DynamicVector<T> result(size);
std::gamma_distribution<> gamma(alpha, 1);
T sum = 0;
for (uint i = 0; i < size; ++i) sum += (result[i] = gamma(gen));
for (uint i = 0; i < size; ++i) result[i] /= sum;
return result;
}
}
namespace DeepLearning {
using namespace Utils::Math;
using namespace Utils::Math::Matrix;
template <typename T = floating_type>
class Network;
template <typename T = floating_type>
class LayerBlock;
namespace Optimizers {
template <typename T>
struct Optimizer {
typedef T value_type;
virtual ~Optimizer() = default;
virtual void updateSingleWeight(value_type &w, value_type grad) = 0;
virtual void preUpdate() = 0;
virtual void postEpoch() = 0;
virtual void printStats(std::ostream &out) const = 0;
};
template <typename T>
struct SGD : public Optimizer<T> {
typedef Optimizer<T> Base;
typedef typename Base::value_type value_type;
double learning_rate, decay;
explicit SGD(double learning_rate, double decay_factor=1.0): learning_rate(learning_rate), decay(decay_factor) {}
SGD(const SGD &o) = default;
~SGD() override {
this->printStats(std::cerr);
}
void updateSingleWeight(value_type &w, value_type grad) override {
w -= grad*learning_rate;
}
void postEpoch() override {
learning_rate *= decay;
}
void preUpdate() override {
}
void printStats(std::ostream &out) const override {
out << "SGD Destructed:\n learning rate: " << learning_rate << ", decay: " << decay << std::endl << std::defaultfloat;
}
};
template <typename T>
struct Adam : public Optimizer<T> {
typedef Optimizer<T> Base;
typedef typename Base::value_type value_type;
double learning_rate, beta1, beta2, eps;
const double init_lr;
value_type* m,* v;
uint updates = 0, currentParam = 0;
explicit Adam(size_type totalParams, double learning_rate=.001, double beta1=.9, double beta2=.999, double eps=1e-7):
learning_rate(learning_rate), beta1(beta1), beta2(beta2), eps(eps), init_lr(learning_rate) {
m = new value_type[totalParams*2];
v = m + totalParams;
std::fill(m, m+totalParams*2, 0.0);
}
~Adam() override {
delete[] m;
this->printStats(std::cerr);
}
void updateSingleWeight(value_type &w, value_type grad) override {
m[currentParam] = beta1 * m[currentParam] + (1.0 - beta1) * grad;
v[currentParam] = beta2 * v[currentParam] + (1.0 - beta2) * grad * grad;
w -= learning_rate * m[currentParam] / (std::sqrt(v[currentParam]) + eps);
++currentParam;
}
void postEpoch() override {
}
void preUpdate() override {
currentParam = 0;
if (updates)
learning_rate = init_lr * sqrt(1.0 - std::pow(beta2, updates)) / (1.0 - std::pow(beta1, updates));
++updates;
}
void printStats(std::ostream &out) const override {
out << "Adam Destructed:\n updates: " << updates << ", initial learning rate: ";
out << init_lr << ", current learning rate: ";
out << learning_rate << ", beta1: ";
out << beta1 << ", beta2: ";
out << beta2 << ", eps: ";
out << eps << std::endl;
out << std::defaultfloat;
}
};
}
namespace Activation {
enum ActivationType: uint {
SIGMOID = 1,
RELU = 2,
SOFTMAX = 3,
TANH = 4
};
template<
typename T
>
struct Sigmoid {
typedef T value_type;
typedef value_type* Data;
constexpr static value_type sigmoid(value_type x) {
return 1.0 / (1.0 + std::exp(-x));
}
constexpr static void f(Data in, Data out, size_type n) {
std::transform(in, in + n, out, sigmoid);
}
constexpr static void fd(Data out, Data deltaIn, Data deltaOut, size_type n) {
for (size_type i = 0; i < n; ++i) deltaOut[i] = out[i] * (1.0 - out[i]) * deltaIn[i];
}
};
template<
typename T
>
struct Tanh {
typedef T value_type;
typedef value_type* Data;
constexpr static void f(Data in, Data out, size_type n) {
for (size_type i = 0; i < n; ++i) out[i] = std::tanh(in[i]);
}
constexpr static void fd(Data out, Data deltaIn, Data deltaOut, size_type n) {
for (size_type i = 0; i < n; ++i) deltaOut[i] = (1.0 - out[i]*out[i]) * deltaIn[i];
}
};
template<
typename T
>
struct ReLU {
typedef T value_type;
typedef value_type* Data;
constexpr static void f(Data in, Data out, size_type n) {
for (size_type i = 0; i < n; ++i) out[i] = in[i] > 0.0? in[i]: 0.0;
}
constexpr static void fd(Data out, Data deltaIn, Data deltaOut, size_type n) {
for (size_type i = 0; i < n; ++i) deltaOut[i] = out[i]? deltaIn[i]: 0.0;
}
};
template<
typename T
>
struct SoftMax {
typedef T value_type;
typedef value_type* Data;
constexpr static void f(Data in, Data out, size_type n) {
value_type sum = 0.0, max = *std::max_element(in, in+n);
for (size_type i = 0; i < n; ++i) {
sum += (out[i] = std::exp(in[i] - max));
}
for (size_type i = 0; i < n; ++i) {
//std::cout << "out: " << out[i] << " = exp(" << in[i] << " - max)\n";
out[i] /= sum;
}
}
constexpr static void fd(Data out, Data deltaIn, Data deltaOut, size_type n) {
value_type jac;
for (size_type i = 0; i < n; ++i) {
deltaOut[i] = 0.0;
if (!deltaIn[i]) continue;
for (size_type j = 0; j < n; ++j) {
jac = i == j? out[i] * (1.0 - out[i]): -out[i] * out[j];
deltaOut[i] += jac * out[j];
}
deltaOut[i] *= deltaIn[i];
}
}
};
template <typename T>
static constexpr
std::pair<
std::function<void(T*, T*, size_type)>,
std::function<void(T*, T*, T*, size_type)>
> getActivation(ActivationType t) {
switch (t) {
case SIGMOID:
return {Sigmoid<T>::f, Sigmoid<T>::fd};
case RELU:
return {ReLU<T>::f, ReLU<T>::fd};
case SOFTMAX:
return {SoftMax<T>::f, SoftMax<T>::fd};
case TANH:
return {Tanh<T>::f, Tanh<T>::fd};
default:
return {nullptr, nullptr};
}
}
static constexpr const char* getActivationName(ActivationType t) {
switch (t) {
case SIGMOID:
return "Sigmoid";
case RELU:
return "ReLU";
case SOFTMAX:
return "SoftMax";
case TANH:
return "Tanh";
default:
return "";
}
}
}
namespace Initializers {
template <typename MAT, typename T_M = typename MAT::value_type>
constexpr static void xavier(MAT &matrix, size_type fanIn, size_type fanOut, std::mt19937 &gen) {
const T_M xv = 2.449489742783178 / std::sqrt(static_cast<T_M>(fanIn + fanOut));
std::uniform_real_distribution<T_M> dis(-xv, xv);
for (size_type i = 0; i < matrix.rows(); ++i) {
for (size_type j = 0; j < matrix.columns(); ++j) {
matrix(i, j) = dis(gen);
}
}
}
}
template <
typename T = floating_type
>
class Layer {
public:
typedef T value_type;
typedef value_type* Data;
typedef DynamicMatrix<value_type> Matrix;
typedef DynamicVector<value_type> Vector;
protected:
constexpr explicit Layer(const Shape3D &outputSize, size_type params, const char* name): output_size(outputSize), params(params), name(name) {}