forked from PrincetonVision/marvin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marvin.hpp
8541 lines (7369 loc) · 386 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
#ifndef MARVIN_HPP
#define MARVIN_HPP
/*
* ----------------------------------------------------------------------------
* Marvin: A Minimalist GPU-only N-Dimensional ConvNets Framework
* Copyright (C) 2016 AutoX, Inc.
* ----------------------------------------------------------------------------
*/
#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) (marvin::cpu_half2float(x))
#define CPUCompute2StorageT(x) (marvin::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
#if CUDA_VERSION >= 8000
#define CUBLAS_DATA_HALF CUDA_R_16F
#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 <cuda.h>
#include <cublas_v2.h>
#include <curand.h>
#include <cudnn.h>
#include <sys/time.h>
#define USE_OPENCV 0
#if USE_OPENCV
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#endif
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_MIN, 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 error_code) {
if (error_code != cudaSuccess) {
std::cerr << "CUDA failure at LINE " << lineNumber << ": cudaError code " << error_code << ": ";
std::string msg;
switch(error_code){
case cudaSuccess: //0
msg = "The API call returned with no errors. In the case of query calls, this can also mean that the operation being queried is complete (see ::cudaEventQuery() and ::cudaStreamQuery())."; break;
case cudaErrorMissingConfiguration: //1
msg = "The device function being invoked (usually via ::cudaLaunchKernel()) was not previously configured via the ::cudaConfigureCall() function."; break;
case cudaErrorMemoryAllocation: //2
msg = "The API call failed because it was unable to allocate enough memory to perform the requested operation."; break;
case cudaErrorInitializationError: //3
msg = "The API call failed because the CUDA driver and runtime could not be initialized."; break;
case cudaErrorLaunchFailure: //4,
msg = "An exception occurred on the device while executing a kernel. Common causes include dereferencing an invalid device pointer and accessing out of bounds shared memory. The device cannot be used until ::cudaThreadExit() is called. All existing device memory allocations are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorPriorLaunchFailure : //5,
msg = "This indicated that a previous kernel launch failed. This was previously used for device emulation of kernel launches. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorLaunchTimeout: //6,
msg = "This indicates that the device kernel took too long to execute. This can only occur if timeouts are enabled - see the device property \ref ::cudaDeviceProp::kernelExecTimeoutEnabled kernelExecTimeoutEnabled for more information. The device cannot be used until ::cudaThreadExit() is called. All existing device memory allocations are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorLaunchOutOfResources: //7,
msg = "This indicates that a launch did not occur because it did not have appropriate resources. Although this error is similar to ::cudaErrorInvalidConfiguration, this error usually indicates that the user has attempted to pass too many arguments to the device kernel, or the kernel launch specifies too many threads for the kernel's register count."; break;
case cudaErrorInvalidDeviceFunction : // 8,
msg = "The requested device function does not exist or is not compiled for the proper device architecture."; break;
case cudaErrorInvalidConfiguration: //9,
msg = "This indicates that a kernel launch is requesting resources that can never be satisfied by the current device. Requesting more shared memory per block than the device supports will trigger this error, as will requesting too many threads or blocks. See ::cudaDeviceProp for more device limitations."; break;
case cudaErrorInvalidDevice : // 10,
msg = "This indicates that the device ordinal supplied by the user does not correspond to a valid CUDA device."; break;
case cudaErrorInvalidValue : // 11,
msg = "This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values."; break;
case cudaErrorInvalidPitchValue : // 12,
msg = "This indicates that one or more of the pitch-related parameters passed to the API call is not within the acceptable range for pitch."; break;
case cudaErrorInvalidSymbol : // 13,
msg = "This indicates that the symbol name/identifier passed to the API call is not a valid name or identifier."; break;
case cudaErrorMapBufferObjectFailed : // 14,
msg = "This indicates that the buffer object could not be mapped."; break;
case cudaErrorUnmapBufferObjectFailed : // 15,
msg = "This indicates that the buffer object could not be unmapped."; break;
case cudaErrorInvalidHostPointer : // 16,
msg = "This indicates that at least one host pointer passed to the API call is not a valid host pointer."; break;
case cudaErrorInvalidDevicePointer : // 17,
msg = "This indicates that at least one device pointer passed to the API call is not a valid device pointer."; break;
case cudaErrorInvalidTexture : // 18,
msg = "This indicates that the texture passed to the API call is not a valid texture."; break;
case cudaErrorInvalidTextureBinding : // 19,
msg = "This indicates that the texture binding is not valid. This occurs if you call ::cudaGetTextureAlignmentOffset() with an unbound texture."; break;
case cudaErrorInvalidChannelDescriptor : // 20,
msg = "This indicates that the channel descriptor passed to the API call is not valid. This occurs if the format is not one of the formats specified by ::cudaChannelFormatKind, or if one of the dimensions is invalid."; break;
case cudaErrorInvalidMemcpyDirection : // 21,
msg = "This indicates that the direction of the memcpy passed to the API call is not one of the types specified by ::cudaMemcpyKind."; break;
case cudaErrorAddressOfConstant : // 22,
msg = "This indicated that the user has taken the address of a constant variable, which was forbidden up until the CUDA 3.1 release. [deprecated] This error return is deprecated as of CUDA 3.1. Variables in constant memory may now have their address taken by the runtime via ::cudaGetSymbolAddress()."; break;
case cudaErrorTextureFetchFailed : // 23,
msg = "This indicated that a texture fetch was not able to be performed. This was previously used for device emulation of texture operations. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorTextureNotBound : // 24,
msg = "This indicated that a texture was not bound for access. This was previously used for device emulation of texture operations. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorSynchronizationError : // 25,
msg = "This indicated that a synchronization operation had failed. This was previously used for some device emulation functions. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorInvalidFilterSetting : // 26,
msg = "This indicates that a non-float texture was being accessed with linear filtering. This is not supported by CUDA."; break;
case cudaErrorInvalidNormSetting : // 27,
msg = "This indicates that an attempt was made to read a non-float texture as a normalized float. This is not supported by CUDA."; break;
case cudaErrorMixedDeviceExecution : // 28,
msg = "Mixing of device and device emulation code was not allowed. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorCudartUnloading : // 29,
msg = "This indicates that a CUDA Runtime API call cannot be executed because it is being called during process shut down, at a point in time after CUDA driver has been unloaded."; break;
case cudaErrorUnknown : // 30,
msg = "This indicates that an unknown internal error has occurred."; break;
case cudaErrorNotYetImplemented : // 31,
msg = "This indicates that the API call is not yet implemented. Production releases of CUDA will never return this error. [deprecated] This error return is deprecated as of CUDA 4.1."; break;
case cudaErrorMemoryValueTooLarge : // 32,
msg = "his indicated that an emulated device pointer exceeded the 32-bit address range. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorInvalidResourceHandle : // 33,
msg = "This indicates that a resource handle passed to the API call was not valid. Resource handles are opaque types like ::cudaStream_t and ::cudaEvent_t."; break;
case cudaErrorNotReady : // 34,
msg = "This indicates that asynchronous operations issued previously have not completed yet. This result is not actually an error, but must be indicated differently than ::cudaSuccess (which indicates completion). Calls that may return this value include ::cudaEventQuery() and ::cudaStreamQuery()."; break;
case cudaErrorInsufficientDriver : // 35,
msg = "This indicates that the installed NVIDIA CUDA driver is older than the CUDA runtime library. This is not a supported configuration. Users should install an updated NVIDIA display driver to allow the application to run."; break;
case cudaErrorSetOnActiveProcess : // 36,
msg = "This indicates that the user has called ::cudaSetValidDevices(), ::cudaSetDeviceFlags(), ::cudaD3D9SetDirect3DDevice(), ::cudaD3D10SetDirect3DDevice, ::cudaD3D11SetDirect3DDevice(), or ::cudaVDPAUSetVDPAUDevice() after initializing the CUDA runtime by calling non-device management operations (allocating memory and launching kernels are examples of non-device management operations). This error can also be returned if using runtime/driver interoperability and there is an existing ::CUcontext active on the host thread."; break;
case cudaErrorInvalidSurface : // 37,
msg = "This indicates that the surface passed to the API call is not a valid surface."; break;
case cudaErrorNoDevice : // 38,
msg = "This indicates that no CUDA-capable devices were detected by the installed CUDA driver."; break;
case cudaErrorECCUncorrectable : // 39,
msg = "This indicates that an uncorrectable ECC error was detected during execution."; break;
case cudaErrorSharedObjectSymbolNotFound : // 40,
msg = "This indicates that a link to a shared object failed to resolve."; break;
case cudaErrorSharedObjectInitFailed : // 41,
msg = "This indicates that initialization of a shared object failed."; break;
case cudaErrorUnsupportedLimit : // 42,
msg = "This indicates that the ::cudaLimit passed to the API call is not supported by the active device."; break;
case cudaErrorDuplicateVariableName : // 43,
msg = "This indicates that multiple global or constant variables (across separate CUDA source files in the application) share the same string name."; break;
case cudaErrorDuplicateTextureName : // 44,
msg = "This indicates that multiple textures (across separate CUDA source files in the application) share the same string name."; break;
case cudaErrorDuplicateSurfaceName : // 45,
msg = "This indicates that multiple surfaces (across separate CUDA source files in the application) share the same string name."; break;
case cudaErrorDevicesUnavailable : // 46,
msg = "This indicates that all CUDA devices are busy or unavailable at the current time. Devices are often busy/unavailable due to use of ::cudaComputeModeExclusive, ::cudaComputeModeProhibited or when long running CUDA kernels have filled up the GPU and are blocking new work from starting. They can also be unavailable due to memory constraints on a device that already has active CUDA work being performed."; break;
case cudaErrorInvalidKernelImage : // 47,
msg = "This indicates that the device kernel image is invalid."; break;
case cudaErrorNoKernelImageForDevice : // 48,
msg = "there is no kernel image available that is suitable for the device. This can occur when a user specifies code generation options for a particular CUDA source file that do not include the corresponding device configuration."; break;
case cudaErrorIncompatibleDriverContext: // 49,
msg = "the current context is not compatible with this the CUDA Runtime. This can only occur if you are using CUDA Runtime/Driver interoperability and have created an existing Driver context using the driver API. The Driver context may be incompatible either because the Driver context was created using an older version of the API, because the Runtime API call expects a primary driver context and the Driver context is not primary, or because the Driver context has been destroyed. Please see ref CUDART_DRIVER Interactions with the CUDA Driver API for more information."; break;
case cudaErrorPeerAccessAlreadyEnabled : // 50,
msg = "a call to ::cudaDeviceEnablePeerAccess() is trying to re-enable peer addressing on from a context which has already had peer addressing enabled."; break;
case cudaErrorPeerAccessNotEnabled : // 51,
msg = "::cudaDeviceDisablePeerAccess() is trying to disable peer addressing which has not been enabled yet via ::cudaDeviceEnablePeerAccess()."; break;
case cudaErrorDeviceAlreadyInUse : // 54,
msg = "a call tried to access an exclusive-thread device that is already in use by a different thread."; break;
case cudaErrorProfilerDisabled : // 55,
msg = "This indicates profiler is not initialized for this run. This can happen when the application is running with external profiling tools like visual profiler."; break;
case cudaErrorProfilerNotInitialized : // 56,
msg = "[deprecated] This error return is deprecated as of CUDA 5.0. It is no longer an error to attempt to enable/disable the profiling via ::cudaProfilerStart or ::cudaProfilerStop without initialization."; break;
case cudaErrorProfilerAlreadyStarted : // 57,
msg = "[deprecated] This error return is deprecated as of CUDA 5.0. It is no longer an error to call cudaProfilerStart() when profiling is already enabled."; break;
case cudaErrorProfilerAlreadyStopped : //58,
msg = "[deprecated] This error return is deprecated as of CUDA 5.0. It is no longer an error to call cudaProfilerStop() when profiling is already disabled."; break;
case cudaErrorAssert : //59,
msg = "An assert triggered in device code during kernel execution. The device cannot be used again until ::cudaThreadExit() is called. All existing allocations are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorTooManyPeers : // 60,
msg = "the hardware resources required to enable peer access have been exhausted for one or more of the devices passed to ::cudaEnablePeerAccess()."; break;
case cudaErrorHostMemoryAlreadyRegistered: // 61,
msg = "the memory range passed to ::cudaHostRegister() has already been registered."; break;
case cudaErrorHostMemoryNotRegistered : // 62,
msg = "the pointer passed to ::cudaHostUnregister() does not correspond to any currently registered memory region."; break;
case cudaErrorOperatingSystem : // 63,
msg = "an OS call failed."; break;
case cudaErrorPeerAccessUnsupported : // 64,
msg = "P2P access is not supported across the given devices."; break;
case cudaErrorLaunchMaxDepthExceeded : // 65,
msg = "a device runtime grid launch did not occur because the depth of the child grid would exceed the maximum supported number of nested grid launches."; break;
case cudaErrorLaunchFileScopedTex : // 66,
msg = "a grid launch did not occur because the kernel uses file-scoped textures which are unsupported by the device runtime. Kernels launched via the device runtime only support textures created with the Texture Object API's."; break;
case cudaErrorLaunchFileScopedSurf : // 67,
msg = "a grid launch did not occur because the kernel uses file-scoped surfaces which are unsupported by the device runtime. Kernels launched via the device runtime only support surfaces created with the Surface Object API's."; break;
case cudaErrorSyncDepthExceeded : // 68,
msg = "a call to ::cudaDeviceSynchronize made from the device runtime failed because the call was made at grid depth greater than than either the default (2 levels of grids) or user specified device limit ::cudaLimitDevRuntimeSyncDepth. To be able to synchronize on launched grids at a greater depth successfully, the maximum nested depth at which ::cudaDeviceSynchronize will be called must be specified with the ::cudaLimitDevRuntimeSyncDepth limit to the ::cudaDeviceSetLimit api before the host-side launch of a kernel using the device runtime. Keep in mind that additional levels of sync depth require the runtime to reserve large amounts of device memory that cannot be used for user allocations."; break;
case cudaErrorLaunchPendingCountExceeded : // 69,
msg = "a device runtime grid launch failed because the launch would exceed the limit ::cudaLimitDevRuntimePendingLaunchCount. For this launch to proceed successfully, ::cudaDeviceSetLimit must be called to set the ::cudaLimitDevRuntimePendingLaunchCount to be higher than the upper bound of outstanding launches that can be issued to the device runtime. Keep in mind that raising the limit of pending device runtime launches will require the runtime to reserve device memory that cannot be used for user allocations."; break;
case cudaErrorNotPermitted : // 70,
msg = "This error indicates the attempted operation is not permitted."; break;
case cudaErrorNotSupported : // 71,
msg = "This error indicates the attempted operation is not supported on the current system or device."; break;
case cudaErrorHardwareStackError : // 72,
msg = "Device encountered an error in the call stack during kernel execution, possibly due to stack corruption or exceeding the stack size limit. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorIllegalInstruction : // 73,
msg = "The device encountered an illegal instruction during kernel execution The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorMisalignedAddress : // 74,
msg = "The device encountered a load or store instruction on a memory address which is not aligned. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorInvalidAddressSpace : // 75,
msg = "While executing a kernel, the device encountered an instruction which can only operate on memory locations in certain address spaces (global, shared, or local), but was supplied a memory address not belonging to an allowed address space. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorInvalidPc : // 76,
msg = "The device encountered an invalid program counter. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorIllegalAddress : // 77,
msg = "The device encountered a load or store instruction on an invalid memory address. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorInvalidPtx : // 78,
msg = "A PTX compilation failed. The runtime may fall back to compiling PTX if an application does not contain a suitable binary for the current device."; break;
case cudaErrorInvalidGraphicsContext : // 79,
msg = "This indicates an error with the OpenGL or DirectX context."; break;
case cudaErrorStartupFailure : // 0x7f,
msg = "This indicates an internal startup failure in the CUDA runtime."; break;
case cudaErrorApiFailureBase : // 10000
msg = "Any unhandled CUDA driver error is added to this value and returned via the runtime. Production releases of CUDA should not return such errors. [deprecated] This error return is deprecated as of CUDA 4.1."; break;
}
std::cerr << msg << 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_MIN")) variable = ElementWise_MIN;
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 set(std::string name, cudnnConvolutionFwdAlgo_t &variable, cudnnConvolutionFwdAlgo_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("implicit_gemm")) variable = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM;
else if (0 == this->member[name]->returnString().compare("implicit_precomp_gemm")) variable = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM;
else if (0 == this->member[name]->returnString().compare("gemm")) variable = CUDNN_CONVOLUTION_FWD_ALGO_GEMM;
else if (0 == this->member[name]->returnString().compare("direct")) variable = CUDNN_CONVOLUTION_FWD_ALGO_DIRECT;
else if (0 == this->member[name]->returnString().compare("fft")) variable = CUDNN_CONVOLUTION_FWD_ALGO_FFT;
else if (0 == this->member[name]->returnString().compare("fft_tiling")) variable = CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING;
else if (0 == this->member[name]->returnString().compare("winograd")) variable = CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD;
else if (0 == this->member[name]->returnString().compare("winograd_nonfused")) variable = CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnConvolutionBwdDataAlgo_t &variable, cudnnConvolutionBwdDataAlgo_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("0")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_0;
else if (0 == this->member[name]->returnString().compare("1")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_1;
else if (0 == this->member[name]->returnString().compare("fft")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT;
else if (0 == this->member[name]->returnString().compare("fft_tiling")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING;
else if (0 == this->member[name]->returnString().compare("winograd")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD;
else if (0 == this->member[name]->returnString().compare("winograd_nonfused")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnConvolutionBwdFilterAlgo_t &variable, cudnnConvolutionBwdFilterAlgo_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("0")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0;
else if (0 == this->member[name]->returnString().compare("1")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1;
else if (0 == this->member[name]->returnString().compare("fft")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT;
else if (0 == this->member[name]->returnString().compare("3")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3;
else if (0 == this->member[name]->returnString().compare("winograd_nonfused")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED;
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));