-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlibartificial.h
More file actions
1732 lines (1630 loc) · 53.5 KB
/
libartificial.h
File metadata and controls
1732 lines (1630 loc) · 53.5 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
/*
* libartificial - Small header-only C library for Artificial Neural Networks
*
* Copyright (c) 2018 Jim Karoukis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#ifndef libartificial_h__
#define libartificial_h__
#ifdef __WIN32__
#if defined(COMPILING_DLL)
#define PUBLIC_API __declspec(dllexport)
#else
#define PUBLIC_API __declspec(dllimport)
#endif
#else
#define PUBLIC_API
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define RESET "\033[0m"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Forward declarations
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// UTILITIES ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// For randomization
static inline void swap(double *restrict a, double *restrict b);
// For normalization
static inline double mean(const int *restrict rows, const double *restrict col);
static inline double stdev(const int *restrict rows, const double *restrict col, const double *restrict mean);
// To convert array of names into array of ints for fast gradient and activations
static inline int *name2int(const int *restrict layers, char funcs[(*layers) + 1][30]);
// Activations
static inline void activate(double *restrict Y, const double *restrict X,
const int *restrict r, const int *restrict c,
const int *restrict f);
// Gradients
static inline void gradient(double *restrict Y, const double *restrict X,
const int *restrict r, const int *restrict c,
const int *restrict f);
// Losses
static inline double rmse(const int *restrict r, const int *restrict c,
const double *restrict Y, const double *restrict Z);
static inline double xentropy(const int *restrict r, const int *restrict c,
const double *restrict Y, const double *restrict Z);
// Store already trained weights (used by cpu_gd_train)
static inline void save_w(double **restrict weights, const int *restrict layers, const int *restrict nodes,
const int *restrict cols_Y, const int *restrict cols_X);
// Convolution utilities
static inline int ***imgpad(int ***restrict images, const int *restrict no_of_images,
const int *restrict img_width,
const int *restrict img_height,
const int *restrict img_channels,
const int *restrict padding, // Zeros around
const int *restrict delete_originals); // 0 = no, 1 = yes (keep only vector in memory)
static inline int **im2col(int ***restrict images,const int *restrict no_of_images,
const int *restrict img_width,
const int *restrict img_height,
const int *restrict img_channels,
const int *restrict spatial, // width and height of weights
const int *restrict stride, // (img_width - spatial + 2 * padding)/stride should be int
const int *restrict padding, // Zeros around
const int *restrict delete_originals); // 0 = no, 1 = yes (keep only vectorized in memory)
// Freedom
static inline void delete_Z(const int *restrict layers, double ***restrict Z);
static inline void delete_img_vector(const int *restrict no_of_images, int **restrict images);
// End of UTILITIES ////////////////////////////////////////////////////////////////////////////////////////////////////
// Training Utilities
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Feedforward pass
static inline void cpu_mm_notrans(const double *restrict A, const double *restrict B, double *restrict C,
const int *restrict rows, const int *restrict cols, const int *restrict coms);
static inline void cpu_feedforward_update(const int *restrict r, const int *restrict cY,
const int *restrict cX, const int *restrict layers,
double ***restrict Z,
const double *restrict X, double **restrict w,
const int *restrict n, const int *restrict f);
static inline double ***cpu_feedforward_cache(const int *restrict r, const int *restrict cY,
const int *restrict cX, const int *restrict layers,
const double *restrict X, double **restrict w,
const int *restrict n, const int *restrict f);
// Deltas
static inline void cpu_mm_notrans_trans(const double *restrict A, const double *restrict B, double *restrict C,
const int *restrict rows, const int *restrict cols, const int *restrict coms);
static inline void cpu_gd_delta(double **restrict d, double **restrict h1, double **restrict h2,
const int *restrict r, const int *restrict c, const int *restrict layers,
const double *restrict Y, double ***restrict Z, double **restrict w,
const int *restrict n, const int *restrict f);
// returns new wb
static inline void cpu_threaded_update(const double *restrict X, const double *restrict d,
double *restrict gw,
double *restrict w,
const int *restrict m,
const int *restrict n,
const int *restrict k,
const double *restrict c);
// End of forward declarations
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC API
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void PUBLIC_API randomize(double *restrict X, const int *restrict rows, const int *restrict cols)
{
// Use a different seed value so that we don't get same
// result each time we run this program
srand(time(NULL));
// Start from the last element and swap one by one. We don't
// need to run for the first element that's why --i > 0
int i = (*rows) * (*cols) - 1;
do {
// Pick a random index from 0 to i
int j = rand() % (i+1);
// Swap X[i] with the element at random index
swap(&X[i], &X[j]);
} while (--i > 0);
}
static inline void PUBLIC_API normalize(double *restrict X, const int *restrict rows, const int *restrict cols)
{
int i, j;
double m = 0.0, sd = 0.0, col[(*rows)];
for (j = 0; j < (*cols); j++) {
if (j != 0) {
for (i = 0; i < (*rows); i++) {
col[i] = X[i * (*cols) + j];
}
m = mean(rows, col);
sd = stdev(rows, col, &m);
i = (*rows) - 1;
for (i = 0; i < (*rows); i++) {
X[i * (*cols) + j] = (X[i * (*cols) + j] - m)/sd;
}
m = 0.0;
sd = 0.0;
}
}
}
static inline double PUBLIC_API rand_normal(const double mu, const double sigma)
{
static double n2 = 0.0;
static double n2_cached = 0.0;
if (!n2_cached) {
double x, y, r;
do
{
x = 2.0 * (double)rand()/RAND_MAX - 1;
y = 2.0 * (double)rand()/RAND_MAX - 1;
r = x*x + y*y;
} while (r == 0.0 || r > 1.0);
double d = sqrt(-2.0 * log(r)/r);
double n1 = x * d;
n2 = y*d;
double result = n1 * sigma + mu;
n2_cached = 1.0;
return result;
} else {
n2_cached = 0.0;
return n2 * sigma + mu;
}
}
// Variance is needed since depending on the data, tanh/relu may give nans.
// Variance < 1 and close to 0.01 if data range too large
static inline PUBLIC_API double **init_w(const double *restrict variance, const int *restrict layers,
const int *restrict nodes, char funcs[(*layers)][30],
const int *restrict cols_Y, const int *restrict cols_X)
{
// l layers
int l = (*layers), prod;
// wb[0] is weights;
// wb[1] is biases;
double **weights = malloc((l + 1) * sizeof(double *));
// For the heuristics of weight initialization
double correction;
do {
int isRelu = strcmp(funcs[l], "relu") + strcmp(funcs[l], "lrelu");
int isTanh = strcmp(funcs[l], "tanh");
switch (l > 0 && l < (*layers)) {
// The statement is false
case 0:
switch (l == 0) {
// The statement is true
case 1:
prod = (*cols_X) * nodes[l];
weights[l] = malloc(prod * sizeof(double));
switch (isRelu == 2 && isTanh == 1) {
// One of the two is false
case 0:
switch (isRelu == 1) {
// Either relu or lrelu
case 1:
// He et al.
correction = sqrt(2.0/(double)(*cols_X));
break;
default:
// Xavier
correction = sqrt(1.0/(double)(*cols_X));
break;
}
break;
default:
correction = sqrt(2.0/(double)(prod));
break;
}
--prod;
do {
weights[l][prod] = correction * rand_normal(0.0, (*variance));
} while (--prod >= 0);
break;
// l = layers
default:
prod = nodes[l-1] * (*cols_Y);
weights[l] = malloc(prod * sizeof(double));
switch (isRelu == 2 && isTanh == 1) {
case 0:
switch (isRelu == 1) {
// Either relu or lrelu
case 1:
// He et al.
correction = sqrt(2.0/(double)nodes[l-1]);
break;
default:
// Xavier
correction = sqrt(1.0/(double)nodes[l-1]);
break;
}
break;
default:
correction = sqrt(2.0/(double)(prod));
break;
}
--prod;
do {
weights[l][prod] = correction * rand_normal(0.0, (*variance));
} while (--prod >= 0);
break;
}
break;
// We are in between input and output
default:
prod = nodes[l-1] * nodes[l];
weights[l] = malloc(prod * sizeof(double));
switch (isRelu == 2 && isTanh == 1) {
case 0:
switch (isRelu == 1) {
// Either relu or lrelu
case 1:
// He et al.
correction = sqrt(2.0/(double)nodes[l-1]);
break;
default:
// Xavier
correction = sqrt(1.0/(double)nodes[l-1]);
break;
}
break;
default:
correction = sqrt(2.0/(double)(prod));
break;
}
--prod;
do {
weights[l][prod] = correction * rand_normal(0.0, (*variance));
} while (--prod >= 0);
break;
}
} while (--l >= 0);
printf(KGRN "\nWeights and biases initialized successfully!\n" RESET);
return weights;
}
// Load pretrained wb files
static inline double PUBLIC_API **load_w(const int *restrict layers, const int *restrict nodes,
const int *restrict cols_Y, const int *restrict cols_X)
{
int l;
char path[1024];
getcwd(path, sizeof(path));
char w_path[1036];
strcpy(w_path, path);
strcat(w_path, "/weights");
double **w = malloc(((*layers) + 1) * sizeof(double *));
w[0] = malloc((*cols_X) * nodes[0] * sizeof(double));
switch ((*layers) > 1) {
case 1:
for (l = 1; l < (*layers); l++) {
w[l] = malloc(nodes[l-1] * nodes[l] * sizeof(double));
}
break;
default:
break;
}
w[(*layers)] = malloc(nodes[(*layers) - 1] * (*cols_Y) * sizeof(double));
FILE *ptr_fp;
for (l = 0; l < (*layers) + 1; l++) {
// This needs to change every time
char w_path_filename[1050];
char number[100];
char filename[15] = "layer_";
sprintf(number, "%d", l);
strcat(filename, number);
strcat(filename, ".bin");
strcpy(w_path_filename, w_path);
strcat(w_path_filename, "/");
strcat(w_path_filename, filename);
if((ptr_fp = fopen(w_path_filename, "rb")) == NULL) {
printf("Unable to open file!\n");
exit(1);
}
if (l == 0) {
if(fread(w[l], (*cols_X) * nodes[l] * sizeof(double), 1, ptr_fp) != 1) {
printf("Read error!\n");
exit(1);
}
fclose(ptr_fp);
} else if (l == (*layers)) {
if(fread(w[l], nodes[l-1] * (*cols_Y) * sizeof(double), 1, ptr_fp) != 1) {
printf("Read error!\n");
exit(1);
}
fclose(ptr_fp);
} else {
if(fread(w[l], nodes[l-1] * nodes[l] * sizeof(double), 1, ptr_fp) != 1) {
printf("Read error!\n");
exit(1);
}
fclose(ptr_fp);
}
}
return w;
}
// Free wb
static inline void PUBLIC_API delete_w(const int *restrict layers, double **restrict w)
{
int l;
for (l = 0; l < (*layers) + 1; l++) free(w[l]);
free(w);
}
// Actual perceptron
static inline double PUBLIC_API *cpu_feedforward_predict(const int *restrict rows, const int *restrict cols_Y,
const int *restrict cols_X, const int *restrict layers,
const double *restrict X, double **restrict w,
const int *restrict nodes, char funcs[(*layers) + 1][30])
{
// l is for layers
// i is for each row * column of X, Y
int l = (*layers);
int r_times_col = (*rows) * (*cols_Y);
int *f;
double *Z_pred = malloc(r_times_col * sizeof(double));
if (Z_pred) {
memset(Z_pred, 0.0, r_times_col * sizeof(double));
} else {
printf(KRED "\nCould not allocate Z_prediction. Aborting...\n" RESET);
abort();
}
// feeds at every layer
double ***Z = malloc(2 * sizeof(double **));
if (Z) {
Z[0] = malloc(((*layers) + 1) * sizeof(double *));
Z[1] = malloc(((*layers) + 1) * sizeof(double *));
if (Z[0] && Z[1]) {
Z[0][l] = malloc(r_times_col * sizeof(double));
Z[1][l] = malloc(r_times_col * sizeof(double));
if (Z[0][l] && Z[1][l]) {
for (l = 0; l < (*layers); l++) {
r_times_col = (*rows) * nodes[l];
Z[0][l] = malloc(r_times_col * sizeof(double));
Z[1][l] = malloc(r_times_col * sizeof(double));
if (Z[0][l] && Z[1][l]) {
memset(Z[0][l], 0.0, r_times_col * sizeof(double));
memset(Z[1][l], 0.0, r_times_col * sizeof(double));
} else {
printf(KRED "\nCould not allocate Zs. Aborting...\n" RESET);
free(Z[0]);
free(Z[1]);
free(Z);
free(Z_pred);
abort();
}
}
} else {
printf(KRED "\nCould not allocate Zs. Aborting...\n" RESET);
free(Z[0]);
free(Z[1]);
free(Z);
free(Z_pred);
abort();
}
} else {
printf(KRED "\nCould not allocate Zs. Aborting...\n" RESET);
free(Z);
free(Z_pred);
abort();
}
} else {
printf(KRED "\nCould not allocate Zs. Aborting...\n" RESET);
free(Z_pred);
abort();
}
f = name2int(layers, funcs);
// Directly manipulates Z
cpu_feedforward_update(rows, cols_Y, cols_X, layers, Z, X, w, nodes, f);
memcpy(Z_pred, Z[1][(*layers)], (*rows) * (*cols_Y) * sizeof(double));
free(f);
delete_Z(layers, Z);
return Z_pred;
}
static inline void PUBLIC_API cpu_gd_train(const int *restrict rows,
const int *restrict cols_Y,
const int *restrict cols_X,
const int *restrict batch,
const int *restrict layers,
const int *restrict nodes,
const double *restrict Y,
const double *restrict X,
double **restrict w,
char funcs[(*layers) + 1][30],
const double *restrict learning_rate,
const int *restrict epochs)
{
// l for layers
// i for rows
// e for epochs
int l, i, for_helper_w, for_helper_batch, e = (*epochs), r_over_b = (*rows)/(*batch);
register int *f;
f = name2int(layers, funcs);
double loss = 0.0;
// For the averaging of deltas in batch/mini-batch
double correction = 1.0;
register double **deltas = malloc(((*layers) + 1) * sizeof(double *));
// The values to be subtracted from weights
register double **grad_w = malloc(((*layers) + 1) * sizeof(double *));
//////////////////////////////////////////////////////////////////
// Gradient of layer's unactivated output
double **help_1 = malloc((*layers) * sizeof(double *));
// Product of next layer's transposed weights and deltas
double **help_2 = malloc((*layers) * sizeof(double *));
// We do not need them at the output layer
//////////////////////////////////////////////////////////////////
if (deltas && grad_w && help_1 && help_2) {
// Allocations
for (l = (*layers) + 1; l--; ) {
if (l == 0) {
for_helper_batch = (*batch) * nodes[l];
for_helper_w = (*cols_X) * nodes[l];
help_1[l] = malloc((*batch) * nodes[l] * sizeof(double));
help_2[l] = malloc((*batch) * nodes[l] * sizeof(double));
memset(help_1[l], 0.0, (*batch) * nodes[l] * sizeof(double));
memset(help_2[l], 0.0, (*batch) * nodes[l] * sizeof(double));
} else if (l == (*layers)) {
for_helper_batch = (*batch) * (*cols_Y);
for_helper_w = nodes[l-1] * (*cols_Y);
} else {
for_helper_batch = (*batch) * nodes[l];
for_helper_w = nodes[l-1] * nodes[l];
help_1[l] = malloc((*batch) * nodes[l] * sizeof(double));
help_2[l] = malloc((*batch) * nodes[l] * sizeof(double));
memset(help_1[l], 0.0, (*batch) * nodes[l] * sizeof(double));
memset(help_2[l], 0.0, (*batch) * nodes[l] * sizeof(double));
}
deltas[l] = malloc(for_helper_batch * sizeof(double));
grad_w[l] = malloc(for_helper_w * sizeof(double));
if (deltas[l] && grad_w[l]) {
memset(deltas[l], 0.0, for_helper_batch * sizeof(double));
memset(grad_w[l], 0.0, for_helper_w * sizeof(double));
} else {
printf(KRED "\nFailed to allocate deltas, gradients or helpers. Aborting...\n" RESET);
free(deltas);
free(grad_w);
free(help_2);
free(help_1);
return;
}
}
} else {
printf(KRED "\nFailed to allocate deltas, gradients or helpers. Aborting...\n" RESET);
return;
}
register double ***Z = cpu_feedforward_cache(rows, cols_Y, cols_X, layers, X, w, nodes, f);
// Big switch in case we have pure batch (do not allocate mini-batches)
switch ((*batch) == (*rows)) {
// True
case 1:
correction = (*learning_rate) * 1.0/(double)(*rows);
// Training
do {
// Find deltas
cpu_gd_delta(deltas, help_1, help_2, rows, cols_Y, layers, Y, Z, w, nodes, f);
// Now we update the weights and biases
// #pragma omp parallel for
for (l = (*layers) + 1; l--; ) {
switch (l == 0) {
case 1:
cpu_threaded_update(X, deltas[l], grad_w[l], w[l], cols_X, &nodes[l], rows, &correction);
continue;
default:
break;
}
switch (l > 0 && l < (*layers)) {
case 1:
cpu_threaded_update(Z[1][l-1], deltas[l], grad_w[l], w[l], &nodes[l-1], &nodes[l], rows, &correction);
continue;
default:
break;
}
switch (l == (*layers)) {
case 1:
cpu_threaded_update(Z[1][l-1], deltas[l], grad_w[l], w[l], &nodes[l-1], cols_Y, rows, &correction);
break;
default:
break;
}
}
// Update Zs with the new wb's
cpu_feedforward_update(rows, cols_Y, cols_X, layers, Z, X, w, nodes, f);
switch (f[(*layers)]) {
// If softmax then cross entropy
case 4:
loss = xentropy(rows, cols_Y, Y, Z[1][(*layers)]);
break;
default:
loss = rmse(rows, cols_Y, Y, Z[1][(*layers)]);
break;
}
if (loss != loss) {
printf(KRED "\nWe got NaN values during training. Aborting...\n" RESET);
for (l = 0; l < (*layers) + 1; l++) {
free(deltas[l]);
free(grad_w[l]);
if (l < (*layers)) {
free(help_2[l]);
free(help_1[l]);
}
}
free(deltas);
free(grad_w);
free(funcs);
free(help_2);
free(help_1);
delete_Z(layers, Z);
return;
}
printf("\nLoss = %.10lf at epoch = %d\n", loss, (*epochs) - e);
} while (--e >= 0);
break;
default:
correction = (*learning_rate) * 1.0/(double)(*batch);
// They need to be allocated once
double **X_batch = malloc(r_over_b * sizeof(double *));
double **Y_batch = malloc(r_over_b * sizeof(double *));
if (X_batch && Y_batch) {
for (i = r_over_b; i--; ) {
X_batch[i] = malloc((*batch) * (*cols_X) * sizeof(double));
Y_batch[i] = malloc((*batch) * (*cols_Y) * sizeof(double));
if (X_batch[i] && Y_batch[i]) {
memset(X_batch[i], 0.0, (*batch) * (*cols_X) * sizeof(double));
memset(Y_batch[i], 0.0, (*batch) * (*cols_Y) * sizeof(double));
} else {
printf(KRED "\nFailed to allocate X or Y batches. Aborting...\n" RESET);
free(X_batch);
free(Y_batch);
return;
}
}
} else {
printf(KRED "\nFailed to allocate X or Y batches. Aborting...\n" RESET);
return;
}
i = r_over_b - 1;
// Fill X_batch, Y_batch
do {
memcpy(X_batch[i], X + i * (*batch) * (*cols_X), (*batch) * (*cols_X) * sizeof(double));
memcpy(Y_batch[i], Y + i * (*batch) * (*cols_Y), (*batch) * (*cols_Y) * sizeof(double));
} while (--i >= 0);
// The perceptrons' outputs
double ***Z_batch = malloc(2 * sizeof(double **));
if (Z_batch) {
// Unactivated
Z_batch[0] = malloc(((*layers) + 1) * sizeof(double *));
// Activated
Z_batch[1] = malloc(((*layers) + 1) * sizeof(double *));
if (Z_batch[0] && Z_batch[1]) {
for (l = (*layers) + 1; l--; ) {
switch (l == (*layers)) {
// Last layer
case 1:
Z_batch[0][l] = malloc((*batch) * (*cols_Y) * sizeof(double));
Z_batch[1][l] = malloc((*batch) * (*cols_Y) * sizeof(double));
if (Z_batch[0][l] && Z_batch[1][l]) {
memset(Z_batch[0][l], 0.0, (*batch) * (*cols_Y) * sizeof(double));
memset(Z_batch[1][l], 0.0, (*batch) * (*cols_Y) * sizeof(double));
} else {
printf(KRED "\nFailed to allocate Z batches. Aborting...\n" RESET);
free(Z_batch[0]);
free(Z_batch[1]);
return;
}
continue;
default:
Z_batch[0][l] = malloc((*batch) * nodes[l] * sizeof(double));
Z_batch[1][l] = malloc((*batch) * nodes[l] * sizeof(double));
if (Z_batch[0][l] && Z_batch[1][l]) {
memset(Z_batch[0][l], 0.0, (*batch) * nodes[l] * sizeof(double));
memset(Z_batch[1][l], 0.0, (*batch) * nodes[l] * sizeof(double));
} else {
printf(KRED "\nFailed to allocate Z batches. Aborting...\n" RESET);
free(Z_batch[0]);
free(Z_batch[1]);
return;
}
continue;
}
}
} else {
printf(KRED "\nFailed to allocate Z batches. Aborting...\n" RESET);
free(Z_batch);
return;
}
} else {
printf(KRED "\nFailed to allocate Z batches. Aborting...\n" RESET);
return;
}
do {
i = r_over_b - 1;
do {
printf(" \t#%d/%d\n", i + 1, r_over_b);
// Fill Z_batch with new Zs
for (l = (*layers); l >= 0; l--) {
switch (l == (*layers)) {
case 1:
memcpy(Z_batch[0][l], Z[0][l] + i * (*batch) * (*cols_Y), (*batch) * (*cols_Y) * sizeof(double));
memcpy(Z_batch[1][l], Z[1][l] + i * (*batch) * (*cols_Y), (*batch) * (*cols_Y) * sizeof(double));
break;
default:
memcpy(Z_batch[0][l], Z[0][l] + i * (*batch) * nodes[l], (*batch) * nodes[l] * sizeof(double));
memcpy(Z_batch[1][l], Z[1][l] + i * (*batch) * nodes[l], (*batch) * nodes[l] * sizeof(double));
break;
}
}
// Fill the deltas
cpu_gd_delta(deltas, help_1, help_2, batch, cols_Y, layers, Y_batch[i], Z_batch, w, nodes, f);
// Now we update the weights and biases
// #pragma omp parallel for
for (l = (*layers) + 1; l--; ) {
switch (l == 0) {
case 1:
cpu_threaded_update(X, deltas[l], grad_w[l], w[l], cols_X, &nodes[l], batch, &correction);
continue;
default:
break;
}
switch (l > 0 && l < (*layers)) {
case 1:
cpu_threaded_update(Z[1][l-1], deltas[l], grad_w[l], w[l], &nodes[l-1], &nodes[l], batch, &correction);
continue;
default:
break;
}
switch (l == (*layers)) {
case 1:
cpu_threaded_update(Z[1][l-1], deltas[l], grad_w[l], w[l], &nodes[l-1], cols_Y, batch, &correction);
break;
default:
break;
}
}
// Do an update of Z's with the new wb's
cpu_feedforward_update(rows, cols_Y, cols_X, layers, Z, X, w, nodes, f);
} while (--i >= 0);
switch (f[(*layers)]) {
// If softmax then cross entropy
case 4:
loss = xentropy(rows, cols_Y, Y, Z[1][(*layers)]);
break;
default:
loss = rmse(rows, cols_Y, Y, Z[1][(*layers)]);
break;
}
if (loss != loss) {
printf(KRED "\nWe got NaN values during training. Aborting...\n" RESET);
// Free before quitting
for (l = 0; l < (*layers) + 1; l++) {
free(Z_batch[0][l]);
free(Z_batch[1][l]);
free(deltas[l]);
free(grad_w[l]);
if (l < (*layers)) {
free(help_2[l]);
free(help_1[l]);
}
}
free(Z_batch[0]);
free(Z_batch[1]);
free(Z_batch);
free(help_2);
free(help_1);
free(deltas);
free(grad_w);
for (i = 0; i < r_over_b; i++) {
free(X_batch[i]);
free(Y_batch[i]);
}
free(Y_batch);
free(X_batch);
free(funcs);
delete_Z(layers, Z);
return;
}
printf("\nLoss = %.10lf at epoch = %d\n", loss, (*epochs) - e);
} while (--e >= 0);
// End of batching
for (l = 0; l < (*layers) + 1; l++) {
free(Z_batch[0][l]);
free(Z_batch[1][l]);
}
free(Z_batch[0]);
free(Z_batch[1]);
free(Z_batch);
for (i = 0; i < r_over_b; i++) {
free(X_batch[i]);
free(Y_batch[i]);
}
free(Y_batch);
free(X_batch);
break;
}
// Save weights and free memory
save_w(w, layers, nodes, cols_Y, cols_X);
// Free the rest
for (l = 0; l < (*layers) + 1; l++) {
free(deltas[l]);
free(grad_w[l]);
if (l < (*layers)) {
free(help_2[l]);
free(help_1[l]);
}
}
free(deltas);
free(grad_w);
free(f);
free(help_2);
free(help_1);
delete_Z(layers, Z);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// End of PUBLIC API ///////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Definitions of forward declarated functions
static inline void swap(double *restrict a, double *restrict b)
{
int temp = *a;
*a = *b;
*b = temp;
}
static inline double mean(const int *restrict rows, const double *restrict col)
{
double sum = 0.0;
int i = (*rows) - 1;
do {
sum += col[i];
} while (--i >= 0);
sum /= (double)(*rows);
return sum;
}
static inline double stdev(const int *restrict rows, const double *restrict col, const double *restrict mean)
{
double sumsq = 0.0, subtr;
int i = (*rows) - 1;
do {
subtr = col[i] - (*mean);
sumsq += subtr * subtr;
} while (--i >= 0);
return sqrt(sumsq/(double)((*rows) - 1));
}
static inline int *name2int(const int *restrict layers, char funcs[(*layers) + 1][30])
{
int *names2ints = malloc(((*layers) + 1) * sizeof(int));
int l = (*layers);
do {
switch (strcmp(funcs[l], "relu")) {
case 0:
names2ints[l] = 0;
continue;
default:
break;
}
switch (strcmp(funcs[l], "logistic")) {
case 0:
names2ints[l] = 1;
continue;
default:
break;
}
switch (strcmp(funcs[l], "linear")) {
case 0:
names2ints[l] = 2;
continue;
default:
break;
}
switch (strcmp(funcs[l], "tanh")) {
case 0:
names2ints[l] = 3;
continue;
default:
break;
}
switch (strcmp(funcs[l], "softmax")) {
case 0:
names2ints[l] = 4;
continue;
default:
break;
}
// Leaky relu
switch (strcmp(funcs[l], "lrelu")) {
case 0:
names2ints[l] = 5;
continue;
default:
break;
}
switch (strcmp(funcs[l], "softplus")) {
case 0:
names2ints[l] = 6;
continue;
default:
break;
}
switch (strcmp(funcs[l], "softsign")) {
case 0:
names2ints[l] = 7;
continue;
default:
break;
}
switch (strcmp(funcs[l], "arctan")) {
case 0:
names2ints[l] = 8;
continue;
default:
break;
}
//Inverse square root with a = 1
switch (strcmp(funcs[l], "isru")) {
case 0:
names2ints[l] = 9;
continue;
default:
break;
}
//Inverse sqrt linear unit \w a=1
switch (strcmp(funcs[l], "isrlu")) {
case 0:
names2ints[l] = 10;
continue;
default:
break;
}
switch (strcmp(funcs[l], "bent")) {
case 0:
names2ints[l] = 11;
continue;
default:
break;
}
switch (strcmp(funcs[l], "sinus")) {
case 0:
names2ints[l] = 12;
continue;
default:
break;
}
switch (strcmp(funcs[l], "sinusc")) {
case 0:
names2ints[l] = 13;
continue;
default:
// Gaussian if nothing else
names2ints[l] = 14;
break;
}
} while (--l >= 0);
return names2ints;
}
static inline void activate(double *restrict Y, const double *restrict X,
const int *restrict r, const int *restrict c,
const int *restrict f)
{
int i = (*r) * (*c) - 1;
switch ((*f)) {
// Relu
case 0:
do {
switch (X[i] < 0.0) {
case 1:
Y[i] = 0.0;
continue;
default:
Y[i] = X[i];
continue;
}
} while (--i >= 0);
return;
// Logistic
case 1: