forked from PrincetonVision/marvin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marvin.hpp
7435 lines (6465 loc) · 324 KB
/
marvin.hpp
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
/*
* ----------------------------------------------------------------------------
* Marvin: A Minimalist GPU-only N-Dimensional ConvNets Framework
* Copyright (C) 2015 Princeton Vision Group
* ----------------------------------------------------------------------------
*/
#if DATATYPE==0
#pragma message "Compiling using StorageT=half ComputeT=float"
#define StorageT half
#define ComputeT float
#define sizeofStorageT 2
#define sizeofComputeT 4
#define CUDNNStorageT CUDNN_DATA_HALF
#define CUDNNConvComputeT CUDNN_DATA_FLOAT
#define CPUStorage2ComputeT(x) (cpu_half2float(x))
#define CPUCompute2StorageT(x) (cpu_float2half(x))
#define GPUStorage2ComputeT(x) (__half2float(x))
#define GPUCompute2StorageT(x) (__float2half(x))
#define GPUgemm Hgemm
#define GPUasum Hasum
#define ISNAN(x) (ishnan(x))
#define ComputeT_MIN FLT_MIN
#include <cuda_fp16.h>
#elif DATATYPE==1
#pragma message "Compiling using StorageT=float ComputeT=float"
#define StorageT float
#define ComputeT float
#define sizeofStorageT 4
#define sizeofComputeT 4
#define CUDNNStorageT CUDNN_DATA_FLOAT
#define CUDNNConvComputeT CUDNN_DATA_FLOAT
#define CPUStorage2ComputeT(x) (x)
#define CPUCompute2StorageT(x) (x)
#define GPUStorage2ComputeT(x) (x)
#define GPUCompute2StorageT(x) (x)
#define GPUgemm cublasSgemm
#define GPUasum cublasSasum
#define ISNAN(x) (std::isnan(x))
#define ComputeT_MIN FLT_MIN
#elif DATATYPE==2
#pragma message "Compiling using StorageT=double ComputeT=double"
#define StorageT double
#define ComputeT double
#define sizeofStorageT 8
#define sizeofComputeT 8
#define CUDNNStorageT CUDNN_DATA_DOUBLE
#define CUDNNConvComputeT CUDNN_DATA_DOUBLE
#define CPUStorage2ComputeT(x) (x)
#define CPUCompute2StorageT(x) (x)
#define GPUStorage2ComputeT(x) (x)
#define GPUCompute2StorageT(x) (x)
#define GPUgemm cublasDgemm
#define GPUasum cublasDasum
#define ISNAN(x) (std::isnan(x))
#define ComputeT_MIN DBL_MIN
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////
// Includes
//////////////////////////////////////////////////////////////////////////////////////////////////
#include <cstdlib>
#include <cstdio>
#include <cstdarg>
#include <cmath>
#include <cfloat>
#include <iostream>
#include <fstream>
#include <sstream>
#include <random>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <thread>
#include <chrono>
#include <future>
#include <cublas_v2.h>
#include <curand.h>
#include <cudnn.h>
#include <sys/time.h>
namespace marvin {
//////////////////////////////////////////////////////////////////////////////////////////////////
// Type definition
//////////////////////////////////////////////////////////////////////////////////////////////////
enum Filler { Xavier, Gaussian, Constant };
enum Pool { Max, Average, Sum };
enum LossObjective { MultinomialLogistic_StableSoftmax, MultinomialLogistic, SmoothL1, Contrastive, EuclideanSSE, HingeL1, HingeL2, SigmoidCrossEntropy, Infogain };
enum Phase { Training, Testing, TrainingTesting };
enum LRPolicy { LR_fixed, LR_step, LR_exp, LR_inv, LR_multistep, LR_poly, LR_sigmoid, LR_cyclical };
enum SolverAlgorithm { SGD, AdaDelta, AdaGrad, Adam, NAG, RMSprop};
enum Regularizer { L2, L1 };
enum LRN { CrossChannel, DivisiveNormalization };
enum ElementWiseOp { ElementWise_EQL, ElementWise_MUL, ElementWise_SUM, ElementWise_MAX };
ComputeT anyval;
ComputeT oneval = 1;
ComputeT zeroval = 0;
const void* one = static_cast<void *>(&oneval);
const void* zero = static_cast<void *>(&zeroval);
const ComputeT* oneComputeT = &oneval;
const ComputeT* zeroComputeT = &zeroval;
//////////////////////////////////////////////////////////////////////////////////////////////////
// Debugging utility
//////////////////////////////////////////////////////////////////////////////////////////////////
void FatalError(const int lineNumber=0) {
std::cerr << "FatalError";
if (lineNumber!=0) std::cerr<<" at LINE "<<lineNumber;
std::cerr << ". Program Terminated." << std::endl;
cudaDeviceReset();
exit(EXIT_FAILURE);
}
void checkCUDA(const int lineNumber, cudaError_t status) {
if (status != cudaSuccess) {
std::cerr << "CUDA failure at LINE " << lineNumber << ": " << status << std::endl;
FatalError();
}
}
void checkCUDNN(const int lineNumber, cudnnStatus_t status) {
if (status != CUDNN_STATUS_SUCCESS) {
std::cerr << "CUDNN failure at LINE " << lineNumber << ": ";
switch (status) {
case CUDNN_STATUS_SUCCESS: std::cerr << "CUDNN_STATUS_SUCCESS" << std::endl; break;
case CUDNN_STATUS_NOT_INITIALIZED: std::cerr << "CUDNN_STATUS_NOT_INITIALIZED" << std::endl; break;
case CUDNN_STATUS_ALLOC_FAILED: std::cerr << "CUDNN_STATUS_ALLOC_FAILED" << std::endl; break;
case CUDNN_STATUS_BAD_PARAM: std::cerr << "CUDNN_STATUS_BAD_PARAM" << std::endl; break;
case CUDNN_STATUS_INTERNAL_ERROR: std::cerr << "CUDNN_STATUS_INTERNAL_ERROR" << std::endl; break;
case CUDNN_STATUS_INVALID_VALUE: std::cerr << "CUDNN_STATUS_INVALID_VALUE" << std::endl; break;
case CUDNN_STATUS_ARCH_MISMATCH: std::cerr << "CUDNN_STATUS_ARCH_MISMATCH" << std::endl; break;
case CUDNN_STATUS_MAPPING_ERROR: std::cerr << "CUDNN_STATUS_MAPPING_ERROR" << std::endl; break;
case CUDNN_STATUS_EXECUTION_FAILED: std::cerr << "CUDNN_STATUS_EXECUTION_FAILED" << std::endl; break;
case CUDNN_STATUS_NOT_SUPPORTED: std::cerr << "CUDNN_STATUS_NOT_SUPPORTED" << std::endl; break;
case CUDNN_STATUS_LICENSE_ERROR: std::cerr << "CUDNN_STATUS_LICENSE_ERROR" << std::endl; break;
}
FatalError();
}
checkCUDA(lineNumber,cudaGetLastError());
}
void checkCUBLAS(const int lineNumber, cublasStatus_t status) {
if (status != CUBLAS_STATUS_SUCCESS) {
std::cerr << "CUBLAS failure at LINE " << lineNumber << ": ";
switch (status) {
case CUBLAS_STATUS_SUCCESS: std::cerr << "CUBLAS_STATUS_SUCCESS" << std::endl; break;
case CUBLAS_STATUS_NOT_INITIALIZED: std::cerr << "CUBLAS_STATUS_NOT_INITIALIZED" << std::endl; break;
case CUBLAS_STATUS_ALLOC_FAILED: std::cerr << "CUBLAS_STATUS_ALLOC_FAILED" << std::endl; break;
case CUBLAS_STATUS_INVALID_VALUE: std::cerr << "CUBLAS_STATUS_INVALID_VALUE" << std::endl; break;
case CUBLAS_STATUS_ARCH_MISMATCH: std::cerr << "CUBLAS_STATUS_ARCH_MISMATCH" << std::endl; break;
case CUBLAS_STATUS_MAPPING_ERROR: std::cerr << "CUBLAS_STATUS_MAPPING_ERROR" << std::endl; break;
case CUBLAS_STATUS_EXECUTION_FAILED: std::cerr << "CUBLAS_STATUS_EXECUTION_FAILED" << std::endl; break;
case CUBLAS_STATUS_INTERNAL_ERROR: std::cerr << "CUBLAS_STATUS_INTERNAL_ERROR" << std::endl; break;
case CUBLAS_STATUS_NOT_SUPPORTED: std::cerr << "CUBLAS_STATUS_NOT_SUPPORTED" << std::endl; break;
case CUBLAS_STATUS_LICENSE_ERROR: std::cerr << "CUBLAS_STATUS_LICENSE_ERROR" << std::endl; break;
}
FatalError();
}
checkCUDA(lineNumber,cudaGetLastError());
}
unsigned long long get_timestamp() {
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (unsigned long long)now.tv_sec * 1000000;
}
unsigned long long ticBegin;
unsigned long long tic() {
ticBegin = get_timestamp();
return ticBegin;
}
unsigned long long toc() {
unsigned long long ticEnd = get_timestamp();
unsigned long long delta = ticEnd - ticBegin;
std::cout << "Time passes " << delta << " microseconds" <<std::endl;
ticBegin = ticEnd;
return delta;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// HALF computation ultility
//////////////////////////////////////////////////////////////////////////////////////////////////
static __inline__ __device__ __host__ int ishnan(half h) {
// When input is NaN, exponent is all ones and mantissa is non-zero.
return (h.x & 0x7c00U) == 0x7c00U && (h.x & 0x03ffU) != 0;
}
half cpu_float2half(float f) {
half ret;
unsigned x = *((int*)(void*)(&f));
unsigned u = (x & 0x7fffffff), remainder, shift, lsb, lsb_s1, lsb_m1;
unsigned sign, exponent, mantissa;
// Get rid of +NaN/-NaN case first.
if (u > 0x7f800000) {
ret.x = 0x7fffU;
return ret;
}
sign = ((x >> 16) & 0x8000);
// Get rid of +Inf/-Inf, +0/-0.
if (u > 0x477fefff) {
ret.x = sign | 0x7c00U;
return ret;
}
if (u < 0x33000001) {
ret.x = (sign | 0x0000);
return ret;
}
exponent = ((u >> 23) & 0xff);
mantissa = (u & 0x7fffff);
if (exponent > 0x70) {
shift = 13;
exponent -= 0x70;
} else {
shift = 0x7e - exponent;
exponent = 0;
mantissa |= 0x800000;
}
lsb = (1 << shift);
lsb_s1 = (lsb >> 1);
lsb_m1 = (lsb - 1);
// Round to nearest even.
remainder = (mantissa & lsb_m1);
mantissa >>= shift;
if (remainder > lsb_s1 || (remainder == lsb_s1 && (mantissa & 0x1))) {
++mantissa;
if (!(mantissa & 0x3ff)) {
++exponent;
mantissa = 0;
}
}
ret.x = (sign | (exponent << 10) | mantissa);
return ret;
}
float cpu_half2float(half h) {
unsigned sign = ((h.x >> 15) & 1);
unsigned exponent = ((h.x >> 10) & 0x1f);
unsigned mantissa = ((h.x & 0x3ff) << 13);
if (exponent == 0x1f) { /* NaN or Inf */
mantissa = (mantissa ? (sign = 0, 0x7fffff) : 0);
exponent = 0xff;
} else if (!exponent) { /* Denorm or Zero */
if (mantissa) {
unsigned int msb;
exponent = 0x71;
do {
msb = (mantissa & 0x400000);
mantissa <<= 1; /* normalize */
--exponent;
} while (!msb);
mantissa &= 0x7fffff; /* 1.mantissa is implicit */
}
} else {
exponent += 0x70;
}
int temp = ((sign << 31) | (exponent << 23) | mantissa);
return *((float*)((void*)&temp));
}
bool operator <(const half& x, const half& y) {
return cpu_half2float(x) < cpu_half2float(y);
}
std::ostream& operator<< (std::ostream& stream, const half& x) {
stream << cpu_half2float(x);
return stream;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// JSON parser
//////////////////////////////////////////////////////////////////////////////////////////////////
enum JSONType { JSON_String, JSON_Bool, JSON_Null, JSON_Number, JSON_Object, JSON_ObjectArray};
// plain object
class JSON{
public:
JSONType type;
std::vector<void*> array;
std::map<std::string, JSON*> member;
~JSON(){
for (int i=0;i<array.size();++i){
if (array[i]!=NULL){
switch(type){
case JSON_String:
delete ((std::string*)(array[i]));
break;
case JSON_Bool:
delete ((bool*)(array[i]));
break;
case JSON_Null:
break;
case JSON_Number:
delete ((ComputeT*)(array[i]));
break;
case JSON_Object:
break;
case JSON_ObjectArray:
delete ((JSON*)(array[i]));
break;
}
}
}
for (std::map<std::string, JSON*>::iterator it = member.begin(); it != member.end(); it++ ){
if (it->second != NULL)
delete it->second;
}
};
std::string returnString(){
if (type!=JSON_String) FatalError(__LINE__);
return *((std::string*)(array[0]));
};
bool returnBool(){
if (type!=JSON_Bool) FatalError(__LINE__);
return *((bool*)(array[0]));
};
ComputeT returnReal(){
if (type!=JSON_Number) FatalError(__LINE__);
return *((ComputeT*)(array[0]));
};
std::vector<int> returnIntVector(){
if (type!=JSON_Number) FatalError(__LINE__);
std::vector<int> v(array.size());
for (int i=0;i<array.size();++i){
v[i] = (int)(*((ComputeT*)(array[i])));
}
return v;
};
std::vector<ComputeT> returnRealVector(){
if (type!=JSON_Number) FatalError(__LINE__);
std::vector<ComputeT> v(array.size());
for (int i=0;i<array.size();++i){
v[i] = (ComputeT)(*((ComputeT*)(array[i])));
}
return v;
};
std::vector<std::string> returnStringVector(){
if (type!=JSON_String) FatalError(__LINE__);
std::vector<std::string> v(array.size());
for (int i=0;i<array.size();++i){
v[i] = *((std::string*)(array[i]));
}
return v;
};
void setOrDie(std::string name, unsigned int &variable){
if (this->member.find(name) == this->member.end()){
FatalError(__LINE__);
}
else variable = (unsigned int)this->member[name]->returnReal();
};
void setOrDie(std::string name, bool &variable){
if (this->member.find(name) == this->member.end()){
FatalError(__LINE__);
}
else variable = this->member[name]->returnBool();
};
void setOrDie(std::string name, std::vector<ComputeT> &variable){
if (this->member.find(name) == this->member.end())
FatalError(__LINE__);
else variable = this->member[name]->returnRealVector();
};
void set(std::string name, bool &variable, bool default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnBool();
};
void set(std::string name, ComputeT &variable, ComputeT default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (ComputeT)(this->member[name]->returnReal());
};
void setOrDie(std::string name, ComputeT &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = (ComputeT)(this->member[name]->returnReal());
};
void set(std::string name, int &variable, int default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (int)(this->member[name]->returnReal());
};
void set(std::string name, double &variable, double default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (double)(this->member[name]->returnReal());
};
void set(std::string name, unsigned int &variable, unsigned int default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (unsigned int)(this->member[name]->returnReal());
};
void setOrDie(std::string name, int &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = (int)(this->member[name]->returnReal());
};
void set(std::string name, std::vector<int> &variable, std::vector<int> default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnIntVector();
};
void set(std::string name, std::vector<ComputeT> &variable, std::vector<ComputeT> default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnRealVector();
};
void set(std::string name, std::vector<std::string> &variable, std::vector<std::string> default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnStringVector();
};
void setOrDie(std::string name, std::vector<std::string> &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = this->member[name]->returnStringVector();
};
void setOrDie(std::string name, std::vector<int> &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = this->member[name]->returnIntVector();
};
void set(std::string name, std::string &variable, std::string default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnString();
};
void setOrDie(std::string name, std::string &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = this->member[name]->returnString();
};
void setOrDie(std::string name, ElementWiseOp &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else if (0 == this->member[name]->returnString().compare("ElementWise_EQL")) variable = ElementWise_EQL;
else if (0 == this->member[name]->returnString().compare("ElementWise_MUL")) variable = ElementWise_MUL;
else if (0 == this->member[name]->returnString().compare("ElementWise_SUM")) variable = ElementWise_SUM;
else if (0 == this->member[name]->returnString().compare("ElementWise_MAX")) variable = ElementWise_MAX;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Filler &variable, Filler default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Xavier")) variable = Xavier;
else if (0 == this->member[name]->returnString().compare("Gaussian")) variable = Gaussian;
else if (0 == this->member[name]->returnString().compare("Constant")) variable = Constant;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Pool &variable, Pool default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Max")) variable = Max;
else if (0 == this->member[name]->returnString().compare("Average")) variable = Average;
else if (0 == this->member[name]->returnString().compare("Sum")) variable = Sum;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void setOrDie(std::string name, LossObjective &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else if (0 == this->member[name]->returnString().compare("MultinomialLogistic_StableSoftmax")) variable = MultinomialLogistic_StableSoftmax;
else if (0 == this->member[name]->returnString().compare("MultinomialLogistic")) variable = MultinomialLogistic;
else if (0 == this->member[name]->returnString().compare("SmoothL1")) variable = SmoothL1;
else if (0 == this->member[name]->returnString().compare("Contrastive")) variable = Contrastive;
else if (0 == this->member[name]->returnString().compare("EuclideanSSE")) variable = EuclideanSSE;
else if (0 == this->member[name]->returnString().compare("HingeL1")) variable = HingeL1;
else if (0 == this->member[name]->returnString().compare("HingeL2")) variable = HingeL2;
else if (0 == this->member[name]->returnString().compare("SigmoidCrossEntropy")) variable = SigmoidCrossEntropy;
else if (0 == this->member[name]->returnString().compare("Infogain")) variable = Infogain;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Phase &variable, Phase default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Training")) variable = Training;
else if (0 == this->member[name]->returnString().compare("Testing")) variable = Testing;
else if (0 == this->member[name]->returnString().compare("TrainingTesting")) variable = TrainingTesting;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, LRPolicy &variable, LRPolicy default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("LR_fixed")) variable = LR_fixed;
else if (0 == this->member[name]->returnString().compare("LR_step")) variable = LR_step;
else if (0 == this->member[name]->returnString().compare("LR_exp")) variable = LR_exp;
else if (0 == this->member[name]->returnString().compare("LR_inv")) variable = LR_inv;
else if (0 == this->member[name]->returnString().compare("LR_multistep")) variable = LR_multistep;
else if (0 == this->member[name]->returnString().compare("LR_poly")) variable = LR_poly;
else if (0 == this->member[name]->returnString().compare("LR_sigmoid")) variable = LR_sigmoid;
else if (0 == this->member[name]->returnString().compare("LR_cyclical")) variable = LR_cyclical;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, SolverAlgorithm &variable, SolverAlgorithm default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("SGD")) variable = SGD;
else if (0 == this->member[name]->returnString().compare("AdaDelta")) variable = AdaDelta;
else if (0 == this->member[name]->returnString().compare("AdaGrad")) variable = AdaGrad;
else if (0 == this->member[name]->returnString().compare("Adam")) variable = Adam;
else if (0 == this->member[name]->returnString().compare("NAG")) variable = NAG;
else if (0 == this->member[name]->returnString().compare("RMSprop")) variable = RMSprop;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Regularizer &variable, Regularizer default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("L2")) variable = L2;
else if (0 == this->member[name]->returnString().compare("L1")) variable = L1;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, LRN &variable, LRN default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("CrossChannel")) variable = CrossChannel;
else if (0 == this->member[name]->returnString().compare("DivisiveNormalization")) variable = DivisiveNormalization;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnBatchNormMode_t &variable, cudnnBatchNormMode_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Spatial")) variable = CUDNN_BATCHNORM_SPATIAL;
else if (0 == this->member[name]->returnString().compare("PerActivation")) variable = CUDNN_BATCHNORM_PER_ACTIVATION;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnPoolingMode_t &variable, cudnnPoolingMode_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("max")) variable = CUDNN_POOLING_MAX;
else if (0 == this->member[name]->returnString().compare("average_include")) variable = CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING;
else if (0 == this->member[name]->returnString().compare("average_exclude")) variable = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnActivationMode_t &variable, cudnnActivationMode_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Sigmoid")) variable = CUDNN_ACTIVATION_SIGMOID;
else if (0 == this->member[name]->returnString().compare("ReLU")) variable = CUDNN_ACTIVATION_RELU;
else if (0 == this->member[name]->returnString().compare("TanH")) variable = CUDNN_ACTIVATION_TANH;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void print(){
switch(type){
case JSON_String:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << "\"" << *((std::string*)(array[i])) << "\"" ;
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Bool:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << ((*((bool*)(array[i])))? "true": "false");
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Null:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << "null";
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Number:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << *((ComputeT*)(array[i]));
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Object:
std::cout<<"{"<<std::endl;
for (std::map<std::string, JSON*>::iterator it = member.begin(); it != member.end(); it++ ){
std::cout << "\t" << it->first << ": ";
it->second->print();
}
std::cout<<"}";
break;
case JSON_ObjectArray:
std::cout<<"["<<std::endl;
for (int i=0;i<array.size();++i){
JSON* p = (JSON*)(array[i]);
p->print();
if (i<array.size()-1) std::cout<<","<<std::endl;
}
std::cout<<"]"<<std::endl;
break;
}
};
void parseNumberOrTextArray(std::string input){
while (input.size()>0){
int e = input.find(",");
if (e==std::string::npos){
e = input.size();
}
std::string first = input.substr(0,e);
if (first[0]=='\"'){
type = JSON_String;
std::string* p = new std::string(first.substr(1,first.size()-2));
array.push_back((void*)p);
}else if (first[0]=='t'){
type = JSON_Bool;
bool* p = new bool(true);
array.push_back((void*)p);
}else if (first[0]=='f'){
type = JSON_Bool;
bool* p = new bool(false);
array.push_back((void*)p);
}else if (first[0]=='n'){
type = JSON_Null;
void* p = NULL;
array.push_back((void*)p);
}else{
type = JSON_Number;
ComputeT* p = new ComputeT(stof(first));
array.push_back((void*)p);
}
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
};
void parseObject(std::string input){
type = JSON_Object;
int b,m,e;
JSON* p;
b = input.find("{");
e = input.find("}");
input = input.substr(b+1,e-b-1);
while (true){
m= input.find(":");
if (std::string::npos==m) break;
std::string name = input.substr(0,m);
name = name.substr(1,m-2);
input = input.substr(m+1);
if (input[0]=='\"'){
e=input.find("\"",1);
p = new JSON;
p->parseNumberOrTextArray(input.substr(0,e+1));
this->member[name] = p;
if (e+2<input.size())
input = input.substr(e+2);
else
break;
}else if (input[0]=='['){
// assume no nested array
input = input.substr(1);
e = input.find("]");
p = new JSON;
p->parseNumberOrTextArray(input.substr(0,e));
this->member[name] = p;
if (e+1<input.size())
input = input.substr(e+2);
else
break;
}else if (input[0]=='f' || input[0]=='t' || input[0]=='.' || input[0]=='-' || ('0'<=input[0] && input[0]<='9')){
e=input.find(",");
if (e==std::string::npos){
e = input.size();
}
p = new JSON;
p->parseNumberOrTextArray(input.substr(0,e));
this->member[name] = p;
if (e+1<input.size())
input = input.substr(e+1);
else
break;
}else{
FatalError(__LINE__);
}
}
};
void parseObjectArray(std::string input){
type = JSON_ObjectArray;
input = input.substr(1,input.size()-2);
while (input.size()>0){
int e = input.find("}")+1;
if (e==std::string::npos){
e = input.size();
}
std::string first = input.substr(0,e);
JSON* pObj = new JSON;
pObj->parseObject(first);
array.push_back((void*)pObj);
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
};
};
#define SetValue(obj,attribute,value) obj->set(#attribute,attribute,value);
#define SetOrDie(obj,attribute) obj->setOrDie(#attribute,attribute);
void parseNetworkJSON(std::string filename, JSON* train_obj, JSON* test_obj, JSON* architecture_obj){
std::ifstream t(filename);
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
str.erase(remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
std::string input = str;
int b,e;
b = input.find("\"train\"");
std::string train_str = input.substr(b+7);
b = train_str.find("{");
e = train_str.find("}");
train_str=train_str.substr(b,e-b+1);
if (train_obj!=NULL) train_obj->parseObject(train_str);
b = input.find("\"test\"");
std::string test_str = input.substr(b+6);
b = test_str.find("{");
e = test_str.find("}");
test_str=test_str.substr(b,e-b+1);
if (test_obj!=NULL) test_obj->parseObject(test_str);
b=input.find("\"layers\"");
input = input.substr(b+9);
e=input.find("}]");
if (architecture_obj!=NULL) architecture_obj->parseObjectArray(input);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Utility
//////////////////////////////////////////////////////////////////////////////////////////////////
bool is_file_exist(const std::string& fileName){
std::ifstream infile(fileName);
return infile.good();
}
void memorySizePrint(size_t bytes){
if (bytes<512){
std::cout<<bytes<<" Bytes";
}else if (bytes<512.0*1024){
std::cout<<(bytes/1024.0)<<" KB";
}else if (bytes<512.0*1024*1024){
std::cout<<(bytes/(1024.0*1024.0))<<" MB";
}else if (bytes<512.0*1024*1024*1024){
std::cout<<(bytes/(1024.0*1024.0*1024.0))<<" GB";
}else if (bytes<512.0*1024*1024*1024*1024){
std::cout<<(bytes/(1024.0*1024.0*1024.0*1024.0))<<" TB";
}else{
std::cout<<(bytes/(1024.0*1024.0*1024.0*1024.0*1024.0))<<" PB";
}
}
void veciPrint(const std::vector<int>& v){
std::cout<<"["<<v.size()<<"]={";
if (v.size()>0) std::cout<<v[0];
if (v.size()>1){
for (int i=1;i<v.size();++i){
std::cout<<","<<v[i];
}
}
std::cout<<"}";
}
void vecfPrint(const std::vector<ComputeT>& v){
std::cout<<"[";
if (v.size()>0) std::cout<<v[0];
if (v.size()>1){
for (int i=1;i<v.size();++i){
std::cout<<","<<v[i];
}
}
std::cout<<"]";
}
std::vector<int> veci(int n, ...){
std::vector<int> v;
if (n==0) return v;
va_list ap;
va_start(ap, n);
for(int i = 0; i < n; i++) {
v.push_back(va_arg(ap, int));
}
va_end(ap);
return v;
}
std::vector<std::string> vecs(int n, ...){
std::vector<std::string> v;
if (n==0) return v;
va_list ap;
va_start(ap, n);
for(int i = 0; i < n; i++) {
v.push_back(std::string(va_arg(ap, char*)));
}
va_end(ap);
return v;
}
std::vector<std::string> getStringVector(std::string input){
std::vector<std::string> ret;
while (input.size()>0){
int e = input.find(",");
if (e==std::string::npos){
e = input.size();
}
std::string first = input.substr(0,e);
ret.push_back(first);
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
return ret;
}
std::vector<std::vector<int> > getIntVectorVector(std::string input){
//remove all space
input.erase(remove_if(input.begin(), input.end(), (int(*)(int))isspace), input.end());
std::vector<std::vector<int> > ret;
while (input.size()>0){
int e;
if (input[0]=='['){
ret.resize(ret.size()+1);
e=0;
}else if (input[0]==','){
e=0;
}else if (input[0]==']'){
e=0;
}else{
e = input.find(",");
if (e==std::string::npos){
e = input.size();
}
int f = input.find("]");
if (f==std::string::npos){
f = input.size();
}
e = min(e,f);
std::string first = input.substr(0,e);
ret[ret.size()-1].push_back(stoi(first));
}
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
return ret;
}
size_t numel(const std::vector<int>& dim){
size_t res = 1;
for (int i=0;i<dim.size();++i) res *= (size_t)(dim[i]);
return res;
}
size_t sizeofitem(const std::vector<int>& dim){
size_t res = 1;
for (int i=1;i<dim.size();++i) res *= (size_t)(dim[i]);
return res;
}
size_t numspel(const std::vector<int>& dim){
size_t res = 1;
for (int i=2;i<dim.size();++i) res *= (size_t)(dim[i]);
return res;
}
bool same_dim(const std::vector<int>& dimA, const std::vector<int>& dimB){
if (dimA.size()!=dimB.size()) return false;
for (int i=0;i<dimA.size();++i){
if (dimA[i]!=dimB[i]) return false;
}
return true;
}
bool same_dim_EC(const std::vector<int>& dimA, const std::vector<int>& dimB){
if (dimA.size()!=dimB.size()) return false;
if (dimA[0]!=dimB[0]) return false;
for (int i=2;i<dimA.size();++i)
if (dimA[i]!=dimB[i])
return false;
return true;
}
size_t checkNaN(StorageT* dataGPU, size_t n){
StorageT* CPUmem = new StorageT[n];
cudaMemcpy(CPUmem, dataGPU, n*sizeofStorageT, cudaMemcpyDeviceToHost);
size_t countNaN = 0;
for (size_t i=0;i<n;++i) if (ISNAN(CPUmem[i])) ++countNaN;
if (countNaN>0){
std::cout<<" checkNaN result: "<<countNaN<<" out of "<<n<<" ("<< 100*ComputeT(countNaN)/n<< "\045) values are NaN, "<<n-countNaN<<" are not NaN."; //<<std::endl;
}
delete [] CPUmem;
return countNaN;
}
std::vector<size_t> randperm(size_t n, std::mt19937& rng){
std::vector<size_t> v(n);
for (size_t i=0;i<n;++i) v[i]=i;
shuffle ( v.begin(), v.end(), rng );
return v;
}
template <typename T>
std::vector<size_t> sort_indexes(const std::vector<T> &v) {
// initialize original index locations
std::vector<size_t> idx(v.size());
for (size_t i = 0; i != idx.size(); ++i) idx[i] = i;
// sort indexes based on comparing values in v
std::sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
return idx;
}
std::string int_to_str(const int i) {
std::ostringstream s;
s << i;
return s.str();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// CUDA kernels
//////////////////////////////////////////////////////////////////////////////////////////////////
#define CUDA_NUM_THREADS 512
#define MAX_NUM_BLOCKS 2880
inline int CUDA_GET_BLOCKS(const size_t N) {
return min(MAX_NUM_BLOCKS, int((N + size_t(CUDA_NUM_THREADS) - 1) / CUDA_NUM_THREADS));
}
inline size_t CUDA_GET_LOOPS(const size_t N) {
size_t total_threads = CUDA_GET_BLOCKS(N)*CUDA_NUM_THREADS;
return (N + total_threads -1)/ total_threads;
}
__global__ void Accuracy_MultinomialLogistic(
size_t CUDA_NUM_LOOPS, size_t N, int C, int M, size_t wN,
const StorageT *pred, const StorageT *label, const StorageT *weight,
const StorageT *weightTensor, StorageT *loss) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +