-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmnistCUDNN.cu
More file actions
executable file
·1819 lines (1515 loc) · 55.9 KB
/
mnistCUDNN.cu
File metadata and controls
executable file
·1819 lines (1515 loc) · 55.9 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
/**
* Copyright 2016 Abhishek Kumar. All rights reserved.
*
* Please refer to the Abhishek Kumar end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/*
* This code implements forward propagation and backward propagation on
* convolutional layer, pooling layer, fully connected layer, activation layer
* and softmax layer. This code learns randomly initialzed weights and then
* stores them into binary files. The network architecture is generic and hence
* this code can be use to create, train and test neural network of any size or
* depth. Code supports both float and double precision and it saves the weights
* accordingly.
*/
/******************************************************************************
* HEADER FILES
*****************************************************************************/
// Standard header files for standard functions
#include <sstream>
#include <fstream>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <cuda.h> // CUDA_VERSION
#include <cudnn.h> // cuDNN routines
#include <cublas_v2.h> // cublas routines
#include "ImageIO.h" // FreeImage library for reading jpg images
#include "error_util.h" // Contains error handling functions
/******************************************************************************
* MACROS
*****************************************************************************/
// #define MATRIX_DATA_TYPE_FLOAT
#define MATRIX_DATA_TYPE_DOUBLE // Use double precision
#ifdef MATRIX_DATA_TYPE_FLOAT
#define MATRIX_DATA_TYPE float
#else
#ifdef MATRIX_DATA_TYPE_DOUBLE
#define MATRIX_DATA_TYPE double
#endif
#endif
#ifndef MATRIX_DATA_TYPE
#error "MATRIX_DATA_TYPE not defined"
#endif
// Handle both precisions in cublas calls
#if defined(MATRIX_DATA_TYPE_FLOAT)
#define CUBLAS_GEMM cublasSgemm
#define CUBLAS_GEAM cublasSgeam
#define CUBLAS_GEMV cublasSgemv
#define CUBLAS_SCAL cublasSscal
#elif defined(MATRIX_DATA_TYPE_DOUBLE)
#define CUBLAS_GEMM cublasDgemm
#define CUBLAS_GEAM cublasDgeam
#define CUBLAS_GEMV cublasDgemv
#define CUBLAS_SCAL cublasDscal
#endif
// MSIZE returns the byte size
#define MSIZE(a) ((a)*sizeof(value_type))
// Define Input Dimensions
#define IMAGE_H (28)
#define IMAGE_W (28)
#define IMAGE_D (1)
#define N (IMAGE_D*IMAGE_H*IMAGE_W) // dimension of training data
// Define 2 args and 3 args max, min functions
#define minn(a,b) (a<b?a:b)
#define maxx(a,b) (a>b?a:b)
#define minnn(a,b,c) (minn(minn(a,b),c))
#define maxxx(a,b,c) (maxx(maxx(a,b),c))
// Define logging functions
//#define print(a) (std::cout<<std::setprecision(0)<<std::fixed<<a)
#define print(a) (std::cout<<std::fixed<<a)
#define println(a) (print(a<<std::endl<<std::flush))
#define DEBUG (0)
//#define VERBOSE (0)
#ifdef VERBOSE
#define vprint(a) print(a)
#define vprintln(a) println(a)
#else
#define vprint(a)
#define vprintln(a)
#endif
#ifdef DEBUG
#define dprint(a) print(a)
#define dprintln(a) println(a)
#else
#define dprint(a)
#define dprintln(a)
#endif
#define EXIT_WAIVED 0
/******************************************************************************
* CONSTANTS AND GLOBALS
*****************************************************************************/
// save and load weights from this path
const std::string weights_folder = "bins/";
// global learning rate which decreases with epochs
double learning_rate;
#define LENET
#ifndef LENET
#define FFNET 100
#endif
#ifdef LENET
#define BASE_GAMMA (0.001)
#define NETWORK_ARCH \
Layer_t<value_type> conv1; conv1.initConvLayer("conv1", 1, 20, 5, 1, IMAGE_H, IMAGE_W, 0, batch_size); \
Layer_t<value_type> pool1; pool1.initPoolLayer("pool1", 2, 2, conv1, batch_size); \
Layer_t<value_type> conv2; conv2.initConvLayer("conv2", pool1.kernel_dim, 50, 5, 1, pool1.out_width, pool1.out_height, pool1.outputs, batch_size); \
Layer_t<value_type> pool2; pool2.initPoolLayer("pool2", 2, 2, conv2, batch_size); \
Layer_t<value_type> fc1; fc1.initFCLayer ("fc1", pool2.outputs, 500, batch_size); \
Layer_t<value_type> fc1act; fc1act.initActLayer("fc1act", fc1.outputs, batch_size); \
Layer_t<value_type> fc2; fc2.initFCLayer ("fc2", fc1act.outputs, 10, batch_size); \
Layer_t<value_type> fc2act; fc2act.initActLayer("fc2act", fc2.outputs, batch_size); \
#define LOAD_DATA (conv1.load() && conv2.load() && fc1.load() && fc2.load())
#define SAVE_DATA (conv1.save() && conv2.save() && fc1.save() && fc2.save())
#define COPY_DATA_TO_DEVICE \
conv1.copyDataToDevice(); \
conv2.copyDataToDevice(); \
fc1.copyDataToDevice(); \
fc2.copyDataToDevice(); \
#define COPY_DATA_TO_HOST \
conv1.copyDataToHost(); \
conv2.copyDataToHost(); \
fc1.copyDataToHost(); \
fc2.copyDataToHost(); \
#define LAYER_NAMES \
conv1, pool1, conv2, pool2, fc1, fc1act, fc2, fc2act
#define LAYER_NAMES_WITH_TYPE \
Layer_t<value_type>& conv1, \
Layer_t<value_type>& pool1, \
Layer_t<value_type>& conv2, \
Layer_t<value_type>& pool2, \
Layer_t<value_type>& fc1, \
Layer_t<value_type>& fc1act,\
Layer_t<value_type>& fc2, \
Layer_t<value_type>& fc2act \
#endif
#ifdef FFNET
#define BASE_GAMMA (0.0001)
#define NETWORK_ARCH \
Layer_t<value_type> fc1; fc1.initFCLayer( "fc1", N, FFNET, batch_size); \
Layer_t<value_type> fc1act; fc1act.initActLayer("fc1act", fc1.outputs, batch_size); \
Layer_t<value_type> fc2; fc2.initFCLayer( "fc2", fc1act.outputs, 10, batch_size); \
Layer_t<value_type> fc2act; fc2act.initActLayer("fc2act", fc2.outputs, batch_size); \
#define LOAD_DATA (fc1.load() && fc2.load())
#define SAVE_DATA (fc1.save() && fc2.save())
#define COPY_DATA_TO_DEVICE \
fc1.copyDataToDevice(); \
fc2.copyDataToDevice(); \
#define COPY_DATA_TO_HOST \
fc1.copyDataToHost(); \
fc2.copyDataToHost(); \
#define LAYER_NAMES \
fc1, fc1act, fc2, fc2act
#define LAYER_NAMES_WITH_TYPE \
Layer_t<value_type>& fc1, \
Layer_t<value_type>& fc1act,\
Layer_t<value_type>& fc2, \
Layer_t<value_type>& fc2act \
#endif
/******************************************************************************
* HELPER FUNCTIONS for classes
*****************************************************************************/
void get_path(std::string& sFilename, const char *fname, const char *pname)
{
sFilename = (std::string("datav5/") + std::string(fname));
}
template <typename value_type>
void printHostVector(std::string str, int size, value_type* vec){
println(str<<" ("<<size<<") ");
for (int i = 0; i < minn(size,400); i++)
{
print(vec[i] << " ");
}
println(" ");
}
template <typename value_type>
void printDeviceVector(std::string str, int size, value_type* vec_d, int n=1)
{
for (int i = 0; i < n; ++i)
{ value_type *vec;
vec = new value_type[size];
cudaDeviceSynchronize();
cudaMemcpy(vec, vec_d+i*size, MSIZE(size), cudaMemcpyDeviceToHost);
printHostVector(str, size, vec);
delete [] vec;
}
}
// IO utils
template <class value_type>
void readBinaryFile(const char* fname, int size, value_type* data_h)
{
std::ifstream dataFile (fname, std::ios::in | std::ios::binary);
std::stringstream error_s;
if (!dataFile)
{
error_s << "Error opening file " << fname;
FatalError(error_s.str());
}
// we assume the data stored is always in float precision
float* data_tmp = new float[size];
int size_b = size*sizeof(float);
if (!dataFile.read ((char*) data_tmp, size_b))
{
error_s << "Error reading file " << fname;
FatalError(error_s.str());
}
for (int i = 0; i < size; i++)
{
data_h[i] = value_type(data_tmp[i]);
}
delete [] data_tmp;
}
template <class value_type>
void readAllocMemcpy(const char* fname, int size, value_type** data_h, value_type** data_d)
{
*data_h = new value_type[size];
readBinaryFile<value_type>(fname, size, *data_h);
int size_b = MSIZE(size);
checkCudaErrors( cudaMalloc(data_d, size_b) );
checkCudaErrors( cudaMemcpy(*data_d, *data_h,
size_b,
cudaMemcpyHostToDevice) );
}
template <class value_type>
void readImage(const char* fname, value_type* imgData_h)
{
// declare a host image object for an 8-bit grayscale image
npp::ImageCPU_8u_C1 oHostSrc;
std::string sFilename(fname);
println("Loading image " << sFilename);
// load gray-scale image from disk
try
{
npp::loadImage(sFilename, oHostSrc);
}
catch (npp::Exception &rException)
{
FatalError(rException.toString());
}
// Plot to console and normalize image to be in range [0,1]
for (int i = 0; i < IMAGE_H; i++)
{
for (int j = 0; j < IMAGE_W; j++)
{
int idx = IMAGE_W*i + j;
imgData_h[idx] = value_type(*(oHostSrc.data() + idx) / double(255));
}
}
}
template <class value_type>
void printDeviceVector(int size, value_type* vec_d)
{
value_type *vec;
vec = new value_type[size];
cudaDeviceSynchronize();
cudaMemcpy(vec, vec_d, MSIZE(size), cudaMemcpyDeviceToHost);
std::cout.precision(5);
std::cout.setf( std::ios::fixed, std::ios::floatfield );
for (int i = 0; i < size; i++)
{
print(value_type(vec[i]) << " ");
}
println(" ");
delete [] vec;
}
/******************************************************************************
* demonstrate different ways of setting tensor descriptor
*****************************************************************************/
//#define SIMPLE_TENSOR_DESCRIPTOR
#define ND_TENSOR_DESCRIPTOR
void setTensorDesc(cudnnTensorDescriptor_t& tensorDesc,
cudnnTensorFormat_t& tensorFormat,
cudnnDataType_t& dataType,
int n,
int c,
int h,
int w)
{
#if SIMPLE_TENSOR_DESCRIPTOR
checkCUDNN( cudnnSetTensor4dDescriptor(tensorDesc,
tensorFormat,
dataType,
n, c,
h,
w ) );
#elif defined(ND_TENSOR_DESCRIPTOR)
const int nDims = 4;
int dimA[nDims] = {n,c,h,w};
int strideA[nDims] = {c*h*w, h*w, w, 1};
checkCUDNN( cudnnSetTensorNdDescriptor(tensorDesc,
dataType,
4,
dimA,
strideA ) );
#else
checkCUDNN( cudnnSetTensor4dDescriptorEx(tensorDesc,
dataType,
n, c,
h, w,
c*h*w, h*w, w, 1) );
#endif
}
/******************************************************************************
* Defining Layer Types
*****************************************************************************/
typedef enum {
CONV_LAYER = 0,
POOL_LAYER = 1,
FC_LAYER = 2,
ACT_LAYER = 3,
NORM_LAYER = 4,
SOFTMAX_LAYER= 5
} LayerType;
/******************************************************************************
* Layer_t struct : contains information about layers
*****************************************************************************/
__global__ void FillOnes(MATRIX_DATA_TYPE *vec, int size)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx >= size)
return;
vec[idx] = 1.0f;
}
template <class value_type>
struct Layer_t
{
LayerType layerType;
std::string layername;
int n; // batch_size
int inputs, outputs, kernel_dim; // linear dimension (i.e. size is kernel_dim * kernel_dim)
int w_size, b_size, d_size;
int in_height, in_width;
int out_height, out_width;
value_type *data_h, *data_d;
value_type *bias_h, *bias_d;
value_type *output_d, *del_d;
value_type *oneVec_d;
// Convolutional Layer
cudnnConvolutionDescriptor_t convDesc;
cudnnTensorDescriptor_t convBiasTensorDesc;
cudnnFilterDescriptor_t convFilterDesc;
cudnnTensorDescriptor_t convSrcTensorDesc, convDstTensorDesc;
cudnnConvolutionFwdAlgo_t convFwdAlgo;
cudnnConvolutionBwdDataAlgo_t convBwdDataAlgo;
cudnnConvolutionBwdFilterAlgo_t convBwdFilterAlgo;
size_t convFwdSizeInBytes, convBwdDataSizeInBytes, convBwdFilterSizeInBytes;
// Pooling Layer
cudnnPoolingDescriptor_t poolDesc;
cudnnTensorDescriptor_t poolSrcTensorDesc, poolDstTensorDesc;
cudnnFilterDescriptor_t poolFilterDesc;
int size, stride;
// Fully Connected Layer
// Activation Layer
cudnnActivationDescriptor_t activDesc;
cudnnTensorDescriptor_t actTensorDesc;
// Normal Layer
// Softmax Layer
cudnnDataType_t dataType;
cudnnTensorFormat_t tensorFormat;
Layer_t() : data_h(NULL), data_d(NULL), bias_h(NULL), bias_d(NULL),
inputs(0), outputs(0), kernel_dim(0)
{
switch (sizeof(value_type))
{
case 4 : dataType = CUDNN_DATA_FLOAT; break;
case 8 : dataType = CUDNN_DATA_DOUBLE; break;
default : FatalError("Unsupported data type");
}
tensorFormat = CUDNN_TENSOR_NCHW;
data_d = bias_d = output_d = del_d = NULL;
oneVec_d = NULL;
n = 0;
convFwdSizeInBytes = convBwdDataSizeInBytes = convBwdFilterSizeInBytes = 0;
};
~Layer_t()
{
if (data_h != NULL) delete [] data_h;
if (bias_h != NULL) delete [] bias_h;
if (data_d != NULL) checkCudaErrors( cudaFree(data_d) );
if (bias_d != NULL) checkCudaErrors( cudaFree(bias_d) );
if (output_d != NULL) checkCudaErrors( cudaFree(output_d) );
if (del_d != NULL) checkCudaErrors( cudaFree(del_d) );
if (layerType == CONV_LAYER){
destroyConvLayer();
} else if (layerType == POOL_LAYER){
destroyPoolLayer();
} else if (layerType == ACT_LAYER || layerType == SOFTMAX_LAYER || layerType == NORM_LAYER){
destroyActLayer();
} else if (layerType == FC_LAYER){
destroyLayer();
}
}
void setHandles(int _n)
{
if (_n==n)
return;
n = _n;
if (oneVec_d != NULL) checkCudaErrors( cudaFree(oneVec_d) );
checkCudaErrors( cudaMalloc(&oneVec_d, MSIZE(n)) );
FillOnes<<<1, n>>>(oneVec_d, n);
if (layerType==CONV_LAYER){
createConvHandles();
} else if (layerType==POOL_LAYER){
createPoolHandles();
} else if (layerType==ACT_LAYER || layerType==SOFTMAX_LAYER || layerType==NORM_LAYER){
createActHandles();
} else { // FC_LAYER
createFCHandles();
}
}
void createPoolHandles(){
int c, h, w;
c = kernel_dim; h=in_height; w=in_width;
setTensorDesc(poolSrcTensorDesc, tensorFormat, dataType, n, c, h, w);
println("pool in >> n:"<<n<<"\tc:"<<c<<"\th:"<<h<<"\tw:"<<w);
const int tensorDims = 4;
int tensorOuputDimA[tensorDims] = {n,c,h,w};
checkCUDNN( cudnnGetPoolingNdForwardOutputDim(poolDesc,
poolSrcTensorDesc,
tensorDims,
tensorOuputDimA) );
n = tensorOuputDimA[0]; c = tensorOuputDimA[1];
h = tensorOuputDimA[2]; w = tensorOuputDimA[3];
println("pool out >> n:"<<n<<"\tc:"<<c<<"\th:"<<h<<"\tw:"<<w);
out_height = h;
out_width = w;
setTensorDesc(poolDstTensorDesc, tensorFormat, dataType, n, c, h, w);
b_size = kernel_dim * out_width * out_height;
outputs = b_size;
inputs = kernel_dim * in_width * in_height;
if (output_d != NULL) checkCudaErrors( cudaFree(output_d) );
if (del_d != NULL) checkCudaErrors( cudaFree(del_d) );
checkCudaErrors( cudaMalloc(&output_d, MSIZE(n*outputs)) );
checkCudaErrors( cudaMalloc(&del_d, MSIZE(n*inputs)) );
}
void createFCHandles(){
if (output_d != NULL) checkCudaErrors( cudaFree(output_d) );
if (del_d != NULL) checkCudaErrors( cudaFree(del_d) );
checkCudaErrors( cudaMalloc(&output_d, MSIZE(n*outputs)) );
checkCudaErrors( cudaMalloc(&del_d, MSIZE(n*inputs)) );
}
void createActHandles(){
int c, h, w;
h = w = 1; c = inputs;
setTensorDesc(actTensorDesc, tensorFormat, dataType, n, c, h, w);
if (output_d != NULL) checkCudaErrors( cudaFree(output_d) );
if (del_d != NULL) checkCudaErrors( cudaFree(del_d) );
checkCudaErrors( cudaMalloc(&output_d, MSIZE(n*outputs)) );
checkCudaErrors( cudaMalloc(&del_d, MSIZE(n*inputs)) );
}
void createConvHandles()
{
int c = inputs;
int h = in_height;
int w = in_width;
println("conv in >> n:"<<n<<"\tc:"<<c<<"\th:"<<h<<"\tw:"<<w);
checkCUDNN(cudnnSetTensor4dDescriptor(convSrcTensorDesc,
tensorFormat,
dataType,
n, c,
h, w));
checkCUDNN(cudnnSetTensor4dDescriptor(convBiasTensorDesc,
tensorFormat,
dataType,
1, outputs,
1, 1));
checkCUDNN(cudnnSetFilter4dDescriptor(convFilterDesc,
dataType,
tensorFormat,
outputs, inputs,
kernel_dim, kernel_dim));
checkCUDNN(cudnnSetConvolution2dDescriptor(convDesc,
0, 0, // padding
stride, stride, // stride
1, 1, // upscaling
CUDNN_CROSS_CORRELATION));
// Find dimension of convolution output
checkCUDNN(cudnnGetConvolution2dForwardOutputDim(convDesc,
convSrcTensorDesc,
convFilterDesc,
&n, &c, &h, &w));
out_width = w;
out_height = h;
println("conv out >> n:"<<n<<"\tc:"<<c<<"\th:"<<h<<"\tw:"<<w);
checkCUDNN(cudnnSetTensor4dDescriptor(convDstTensorDesc,
tensorFormat,
dataType,
n, c,
h, w));
cudnnHandle_t cudnnHandle;
checkCUDNN( cudnnCreate(&cudnnHandle) );
convFwdAlgo = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM;
// checkCUDNN(cudnnGetConvolutionForwardAlgorithm(cudnnHandle,
// convSrcTensorDesc,
// convFilterDesc,
// convDesc,
// convDstTensorDesc,
// CUDNN_CONVOLUTION_FWD_PREFER_FASTEST,
// 0,
// &convFwdAlgo));
checkCUDNN(cudnnGetConvolutionForwardWorkspaceSize(cudnnHandle,
convSrcTensorDesc,
convFilterDesc,
convDesc,
convDstTensorDesc,
convFwdAlgo,
&convFwdSizeInBytes));
convBwdDataAlgo = CUDNN_CONVOLUTION_BWD_DATA_ALGO_0;
// checkCUDNN( cudnnGetConvolutionBackwardDataAlgorithm(cudnnHandle,
// convFilterDesc,
// convDstTensorDesc,
// convDesc,
// convSrcTensorDesc,
// CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST,
// 0,
// &convBwdDataAlgo));
checkCUDNN( cudnnGetConvolutionBackwardDataWorkspaceSize(cudnnHandle,
convFilterDesc,
convDstTensorDesc,
convDesc,
convSrcTensorDesc,
convBwdDataAlgo,
&convBwdDataSizeInBytes
));
convBwdFilterAlgo = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1;
// checkCUDNN( cudnnGetConvolutionBackwardFilterAlgorithm(cudnnHandle,
// convSrcTensorDesc,
// convDstTensorDesc,
// convDesc,
// convFilterDesc,
// CUDNN_CONVOLUTION_BWD_FILTER_PREFER_FASTEST,
// 0,
// &convBwdFilterAlgo));
checkCUDNN( cudnnGetConvolutionBackwardFilterWorkspaceSize(cudnnHandle,
convSrcTensorDesc,
convDstTensorDesc,
convDesc,
convFilterDesc,
convBwdFilterAlgo,
&convBwdFilterSizeInBytes));
//println("handles: "<<(int)convFwdAlgo<<" "<<(int)convBwdDataAlgo<<" "<<(int)convBwdFilterAlgo);
checkCUDNN( cudnnDestroy(cudnnHandle) );
if (data_d != NULL) checkCudaErrors( cudaFree(data_d) );
if (bias_d != NULL) checkCudaErrors( cudaFree(bias_d) );
if (output_d != NULL) checkCudaErrors( cudaFree(output_d) );
if (del_d != NULL) checkCudaErrors( cudaFree(del_d) );
checkCudaErrors( cudaMalloc(&data_d, MSIZE(w_size)) );
checkCudaErrors( cudaMalloc(&bias_d, MSIZE(b_size)) );
checkCudaErrors( cudaMalloc(&output_d, MSIZE(n*outputs*out_height*out_width)) );
checkCudaErrors( cudaMalloc(&del_d, MSIZE(n*d_size)) );
}
void initConvLayer(std::string _layername, int _inputs, int _outputs, int _kernel_dim, int _stride, int _in_height, int _in_width, int _d_size=0, int _batch_size=1)
{
layerType = CONV_LAYER;
layername = _layername;
inputs = _inputs;
outputs = _outputs;
kernel_dim = _kernel_dim;
stride = _stride;
in_width = _in_width;
in_height = _in_height;
w_size = inputs*outputs*kernel_dim*kernel_dim;
b_size = outputs;
d_size = _d_size;
data_h = new value_type[w_size];
bias_h = new value_type[b_size];
// Random Initialization
// TODO : Fix this random initialization
for (int i=0; i<w_size; i++)
data_h[i] = (((value_type)rand())/(rand()+1))/100000;
for (int i=0; i<b_size; i++)
bias_h[i] = (((value_type)rand())/(rand()+1))/100000;
checkCUDNN(cudnnCreateTensorDescriptor(&convSrcTensorDesc));
checkCUDNN(cudnnCreateTensorDescriptor(&convDstTensorDesc));
checkCUDNN(cudnnCreateFilterDescriptor(&convFilterDesc));
checkCUDNN(cudnnCreateConvolutionDescriptor(&convDesc));
checkCUDNN(cudnnCreateTensorDescriptor(&convBiasTensorDesc));
setHandles(_batch_size);
copyDataToDevice();
}
void initPoolLayer(std::string _layername, int _size, int _stride, Layer_t<value_type>& conv, int _batch_size=1)
{
layerType = POOL_LAYER;
layername = _layername;
size = _size;
stride = _stride;
w_size = 0;
kernel_dim = conv.outputs;
in_height = conv.out_height;
in_width = conv.out_width;
checkCUDNN(cudnnCreateTensorDescriptor(&poolSrcTensorDesc));
checkCUDNN(cudnnCreateTensorDescriptor(&poolDstTensorDesc));
checkCUDNN(cudnnCreatePoolingDescriptor(&poolDesc));
checkCUDNN(cudnnSetPooling2dDescriptor(poolDesc,
CUDNN_POOLING_MAX,
CUDNN_PROPAGATE_NAN,
size, size,
0, 0,
stride, stride));
setHandles(_batch_size);
}
void initFCLayer(std::string _layername, int _inputs, int _outputs, int _batch_size=1)
{
layerType = FC_LAYER;
layername = _layername;
inputs = _inputs;
outputs = _outputs;
kernel_dim = 1;
w_size = inputs*outputs*kernel_dim*kernel_dim;
b_size = outputs;
data_h = new value_type[w_size];
bias_h = new value_type[b_size];
// Random Initialization
// TODO : Fix this random initialization
for (int i=0; i<w_size; i++)
data_h[i] = (((value_type)rand())/(rand()+1))/100000;
for (int i=0; i<b_size; i++)
bias_h[i] = (((value_type)rand())/(rand()+1))/100000;
checkCudaErrors( cudaMalloc(&data_d, MSIZE(w_size)) );
checkCudaErrors( cudaMalloc(&bias_d, MSIZE(b_size)) );
setHandles(_batch_size);
copyDataToDevice();
}
void initActLayer(std::string _layername, int _outputs, int _batch_size=1){
initLayer(_layername, ACT_LAYER, _outputs, _batch_size);
}
void initSoftmaxLayer(std::string _layername, int _outputs, int _batch_size=1){
initLayer(_layername, SOFTMAX_LAYER, _outputs, _batch_size);
}
void destroyConvLayer(){
checkCUDNN(cudnnDestroyTensorDescriptor(convSrcTensorDesc));
checkCUDNN(cudnnDestroyTensorDescriptor(convDstTensorDesc));
checkCUDNN(cudnnDestroyFilterDescriptor(convFilterDesc));
checkCUDNN(cudnnDestroyConvolutionDescriptor(convDesc));
checkCUDNN(cudnnDestroyTensorDescriptor(convBiasTensorDesc));
}
void destroyPoolLayer(){
checkCUDNN(cudnnDestroyTensorDescriptor(poolSrcTensorDesc));
checkCUDNN(cudnnDestroyTensorDescriptor(poolDstTensorDesc));
checkCUDNN(cudnnDestroyPoolingDescriptor(poolDesc));
}
void destroyActLayer(){
checkCUDNN( cudnnDestroyActivationDescriptor(activDesc) );
checkCUDNN( cudnnDestroyTensorDescriptor(actTensorDesc) );
}
void destroyLayer(){
}
void copyDataToDevice(){
if (data_h!=NULL) checkCudaErrors( cudaMemcpy(data_d, data_h, MSIZE(w_size), cudaMemcpyHostToDevice) );
if (bias_h!=NULL) checkCudaErrors( cudaMemcpy(bias_d, bias_h, MSIZE(b_size), cudaMemcpyHostToDevice) );
}
void copyDataToHost(){
if (data_h!=NULL) checkCudaErrors( cudaMemcpy(data_h, data_d, MSIZE(w_size), cudaMemcpyDeviceToHost) );
if (bias_h!=NULL) checkCudaErrors( cudaMemcpy(bias_h, bias_d, MSIZE(b_size), cudaMemcpyDeviceToHost) );
}
bool load(){
std::string dtype = (sizeof(value_type)==4?"_float_":"_double_");
return loadWeights(layername+dtype+"weights.bin", w_size, data_h) && loadWeights(layername+dtype+"bias.bin", b_size, bias_h);
}
bool save(){
std::string dtype = (sizeof(value_type)==4?"_float_":"_double_");
return saveWeights(layername+dtype+"weights.bin", w_size, data_h) && saveWeights(layername+dtype+"bias.bin", b_size, bias_h);
}
bool loadWeights(std::string filename, size_t size, value_type* matrix){
filename = weights_folder+filename;
std::ifstream myfile(filename.c_str(), std::ios::in | std::ios::binary);
if (myfile.is_open()){
myfile.read((char*)matrix, MSIZE(size));
return true;
}else{
println("Error reading file "<<filename);
return false;
}
}
bool saveWeights(std::string filename, size_t size, value_type* matrix){
filename = weights_folder+filename;
std::ofstream myfile(filename.c_str(), std::ios::out | std::ios::binary);
if (myfile.is_open()){
myfile.write((char*)matrix, MSIZE(size));
return true;
}else{
println("Error saving file "<<filename);
return false;
}
}
private:
void initLayer(std::string _layername, LayerType _layerType, int _outputs, int _batch_size=1){
layerType = _layerType;
layername = _layername;
inputs = _outputs;
outputs = _outputs;
kernel_dim = 1;
w_size = 0;
b_size = 0;
checkCUDNN( cudnnCreateActivationDescriptor(&activDesc) );
checkCUDNN( cudnnCreateTensorDescriptor(&actTensorDesc) );
checkCUDNN( cudnnSetActivationDescriptor(activDesc,
CUDNN_ACTIVATION_RELU, //CUDNN_ACTIVATION_SIGMOID,
CUDNN_PROPAGATE_NAN,
0.0) );
setHandles(_batch_size);
}
void readAllocInit(const char* fname, int size, value_type** data_h, value_type** data_d)
{
readAllocMemcpy<value_type>(fname, size, data_h, data_d);
}
};
/******************************************************************************
* network_t class : contains all learning functions
*****************************************************************************/
__global__ void getDiffDataD(MATRIX_DATA_TYPE* targets, MATRIX_DATA_TYPE* diffData, int label_count, int _batch_size){
int idx = threadIdx.x;
if (idx>=_batch_size)
return;
const int label_value = static_cast<int>(targets[idx]);
diffData[ idx * label_count + label_value] -= 1;
}
template <class value_type>
class network_t
{
cudnnHandle_t cudnnHandle;
cublasHandle_t cublasHandle;
value_type vOne, vZero;
void createHandles()
{
checkCUDNN( cudnnCreate(&cudnnHandle) );
checkCublasErrors( cublasCreate(&cublasHandle) );
}
void destroyHandles()
{
checkCUDNN( cudnnDestroy(cudnnHandle) );
checkCublasErrors( cublasDestroy(cublasHandle) );
}
public:
network_t()
{
vOne = value_type(1);
vZero = value_type(0);
createHandles();
};
~network_t()
{
destroyHandles();
}
void resize(int size, value_type **data)
{
if (*data != NULL)
{
checkCudaErrors( cudaFree(*data) );
}
checkCudaErrors( cudaMalloc(data, MSIZE(size)) );
}
void addBias(const cudnnTensorDescriptor_t& convDstTensorDesc, Layer_t<value_type>& layer, int c, value_type *data)
{
checkCUDNN( cudnnAddTensor( cudnnHandle,
&vOne,
layer.convBiasTensorDesc,
layer.bias_d,
&vOne,
convDstTensorDesc,
data) );
}
void fullyConnectedForward(Layer_t<value_type>& layer,
int& n,
value_type* srcData)
{
layer.setHandles(n);
// int dim_x = layer.inputs;
// int dim_y = layer.outputs;
// checkCudaErrors( cudaMemcpy(layer.output_d, layer.bias_d, MSIZE(dim_y), cudaMemcpyDeviceToDevice) );
// checkCublasErrors( CUBLAS_GEMV(cublasHandle, CUBLAS_OP_T,
// dim_x, dim_y,
// &vOne,
// layer.data_d, dim_x,
// srcData, 1,
// &vOne,
// layer.output_d, 1) );
// Forward propagate neurons using weights (fc1 = pfc1'*pool2)
checkCudaErrors(CUBLAS_GEMM(cublasHandle, CUBLAS_OP_T, CUBLAS_OP_N,
layer.outputs, n, layer.inputs,
&vOne,
layer.data_d, layer.inputs,
srcData, layer.inputs,
&vZero,
layer.output_d, layer.outputs));
// printDeviceVector("One Vector:\n", n, layer.oneVec_d);
// Add bias using GEMM's "beta" (fc1 += pfc1bias*1_vec')
checkCudaErrors(CUBLAS_GEMM(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N,
layer.outputs, n, 1,
&vOne,
layer.bias_d, layer.outputs,
layer.oneVec_d, 1,
&vOne,
layer.output_d, layer.outputs));
}
void convoluteForward(Layer_t<value_type>& layer,
int& n,
value_type* srcData)
{
layer.setHandles(n);
if (DEBUG) printDeviceVector("Conv Weights:\n", layer.w_size, layer.data_d);
if (DEBUG) printDeviceVector("Conv Bias:\n", layer.b_size, layer.bias_d);
void* workSpace=NULL;
if (layer.convFwdSizeInBytes!=0)
{
checkCudaErrors( cudaMalloc(&workSpace,layer.convFwdSizeInBytes) );
}
checkCUDNN( cudnnConvolutionForward(cudnnHandle,
&vOne,
layer.convSrcTensorDesc,
srcData,
layer.convFilterDesc,
layer.data_d,
layer.convDesc,
layer.convFwdAlgo,
workSpace,
layer.convFwdSizeInBytes,
&vZero,
layer.convDstTensorDesc,
layer.output_d) );
addBias(layer.convDstTensorDesc, layer, layer.outputs, layer.output_d);