-
Notifications
You must be signed in to change notification settings - Fork 22
/
libcudnn.py
1940 lines (1716 loc) · 86 KB
/
libcudnn.py
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
"""
Python interface to the NVIDIA cuDNN library
"""
import sys
import ctypes
import ctypes.util
if sys.platform in ('linux2', 'linux'):
_libcudnn_libname_list = ['libcudnn.so', 'libcudnn.so.6', 'libcudnn.so.6.0.21']
elif sys.platform == 'darwin':
_libcudnn_libname_list = ['libcudnn.dylib', 'libcudnn.6.dylib']
elif sys.platform == 'win32':
_libcudnn_libname_list = ['cudnn64_6.dll']
else:
raise RuntimeError('unsupported platform')
_libcudnn = None
for _libcudnn_libname in _libcudnn_libname_list:
try:
_libcudnn = ctypes.cdll.LoadLibrary(_libcudnn_libname)
except OSError:
pass
else:
break
if _libcudnn is None:
raise OSError('cuDNN library not found')
# cuDNN error
_libcudnn.cudnnGetErrorString.restype = ctypes.c_char_p
_libcudnn.cudnnGetErrorString.argtypes = [ctypes.c_int]
class cudnnError(Exception):
def __init__(self, status):
self.status = status
def __str__(self):
error = _libcudnn.cudnnGetErrorString(self.status)
return '%s' % (error)
# Data layout specification
# cudnnTensorFormat_t is an enumerated type used by
# cudnnSetTensor4dDescriptor() to create a tensor with a pre-defined layout.
cudnnTensorFormat = {
'CUDNN_TENSOR_NCHW': 0, # This tensor format specifies that the data
# is laid out in the following order: image,
# features map, rows, columns. The strides
# are implicitly defined in such a way that
# the data are contiguous in memory with no
# padding between images, feature maps,
# rows, and columns; the columns are the
# inner dimension and the images are the
# outermost dimension.
'CUDNN_TENSOR_NHWC': 1, # This tensor format specifies that the data
# is laid out in the following order: image,
# rows, columns, features maps. The strides
# are implicitly defined in such a way that
# the data are contiguous in memory with no
# padding between images, rows, columns, and
# features maps; the feature maps are the
# inner dimension and the images are the
# outermost dimension.
'CUDNN_TENSOR_NCHW_VECT_C': 2 # This tensor format specifies that the data
# is laid out in the following order: batch
# size, feature maps, rows, columns. However,
# each element of the tensor is a vector of
# multiple feature maps. The length of the
# vector is carried by the data type of the
# tensor. The strides are implicitly defined
# in such a way that the data are contiguous
# in memory with no padding between images,
# feature maps, rows, and columns; the
# columns are the inner dimension and the
# images are the outermost dimension. This
# format is only supported with tensor data
# type CUDNN_DATA_INT8x4.
}
# Data type
# cudnnDataType_t is an enumerated type indicating the data type to which a tensor
# descriptor or filter descriptor refers.
cudnnDataType = {
'CUDNN_DATA_FLOAT': 0, # The data is 32-bit single-precision floating point
# ( float ).
'CUDNN_DATA_DOUBLE': 1, # The data is 64-bit double-precision floating point
# ( double ).
'CUDNN_DATA_HALF': 2, # The data is 16-bit half-precision floating point
# ( half ).
'CUDNN_DATA_INT8': 3, # The data is 8-bit signed integer.
'CUDNN_DATA_INT32': 4, # The data is 32-bit signed integer.
'CUDNN_DATA_INT8x4': 5 # The data is 32-bit element composed of 4 8-bit
# signed integer. This data type is only supported
# with tensor format CUDNN_TENSOR_NCHW_VECT_C.
}
# cudnnAddMode_t is an enumerated type used by cudnnAddTensor() to specify how
# a bias tensor is added to an input/output tensor.
cudnnAddMode = {
'CUDNN_ADD_IMAGE': 0,
'CUDNN_ADD_SAME_HW': 0, # In this mode, the bias tensor is defined as one
# image with one feature map. This image will be
# added to every feature map of every image of the
# input/output tensor.
'CUDNN_ADD_FEATURE_MAP': 1,
'CUDNN_ADD_SAME_CHW': 1, # In this mode, the bias tensor is defined as one
# image with multiple feature maps. This image
# will be added to every image of the input/output
# tensor.
'CUDNN_ADD_SAME_C': 2, # In this mode, the bias tensor is defined as one
# image with multiple feature maps of dimension
# 1x1; it can be seen as an vector of feature maps.
# Each feature map of the bias tensor will be added
# to the corresponding feature map of all height-by-
# width pixels of every image of the input/output
# tensor.
'CUDNN_ADD_FULL_TENSOR': 3 # In this mode, the bias tensor has the same
# dimensions as the input/output tensor. It will be
# added point-wise to the input/output tensor.
}
# cudnnConvolutionMode_t is an enumerated type used by
# cudnnSetConvolutionDescriptor() to configure a convolution descriptor. The
# filter used for the convolution can be applied in two different ways, corresponding
# mathematically to a convolution or to a cross-correlation. (A cross-correlation is
# equivalent to a convolution with its filter rotated by 180 degrees.)
cudnnConvolutionMode = {
'CUDNN_CONVOLUTION': 0, # In this mode, a convolution operation will be done
# when applying the filter to the images.
'CUDNN_CROSS_CORRELATION': 1 # In this mode, a cross-correlation operation will
# be done when applying the filter to the images.
}
# cudnnConvolutionFwdPreference_t is an enumerated type used by
# cudnnGetConvolutionForwardAlgorithm() to help the choice of the algorithm used for the
# forward convolution.
cudnnConvolutionFwdPreference = {
'CUDNN_CONVOLUTION_FWD_NO_WORKSPACE': 0, # In this configuration, the routine
# cudnnGetConvolutionForwardAlgorithm() is guaranteed to return
# an algorithm that does not require any extra workspace to be
# provided by the user.
'CUDNN_CONVOLUTION_FWD_PREFER_FASTEST': 1, # In this configuration, the routine
# cudnnGetConvolutionForwardAlgorithm() will return the fastest
# algorithm regardless how much workspace is needed to execute it.
'CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT': 2 # In this configuration, the routine
# cudnnGetConvolutionForwardAlgorithm() will return the fastest
# algorithm that fits within the memory limit that the user provided.
}
# cudnnConvolutionFwdAlgo_t is an enumerated type that exposes the different algorithm
# available to execute the forward convolution operation.
cudnnConvolutionFwdAlgo = {
'CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM': 0, # This algorithm expresses the convolution
# as a matrix product without actually explicitly forming the matrix
# that holds the input tensor data.
'CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM': 1, # This algorithm expresses the convolution
# as a matrix product without actually explicitly forming the matrix
# that holds the input tensor data, but still needs some memory
# workspace to precompute some indices in order to facilitate the
# implicit construction of the matrix that holds the input tensor data.
'CUDNN_CONVOLUTION_FWD_ALGO_GEMM': 2, # This algorithm expresses the convolution as an
# explicit matrix product. A significant memory workspace is needed to
# store the matrix that holds the input tensor data.
'CUDNN_CONVOLUTION_FWD_ALGO_DIRECT': 3, # This algorithm expresses the convolution as a
# direct convolution (e.g without implicitly or explicitly doing a
# matrix multiplication).
'CUDNN_CONVOLUTION_FWD_ALGO_FFT': 4,
'CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING': 5,
'CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD': 6,
'CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED': 7,
'CUDNN_CONVOLUTION_FWD_ALGO_COUNT': 8
}
cudnnConvolutionBwdDataPreference = {
'CUDNN_CONVOLUTION_BWD_DATA_NO_WORKSPACE': 0,
'CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST': 1,
'CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT': 2
}
cudnnConvolutionBwdDataAlgo = {
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_0': 0,
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_1': 1,
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT': 2,
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING': 3,
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD': 4,
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED': 5,
'CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT': 6
}
cudnnConvolutionBwdFilterPreference = {
'CUDNN_CONVOLUTION_BWD_FILTER_NO_WORKSPACE' : 0,
'CUDNN_CONVOLUTION_BWD_FILTER_PREFER_FASTEST' : 1,
'CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT' : 2,
}
cudnnConvolutionBwdFilterAlgo = {
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0' : 0,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1' : 1,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT' : 2,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3' : 3,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD': 4,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED': 5,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING': 6,
'CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT': 7
}
# cudnnSoftmaxAlgorithm_t is used to select an implementation of the softmax
# function used in cudnnSoftmaxForward() and cudnnSoftmaxBackward().
cudnnSoftmaxAlgorithm = {
'CUDNN_SOFTMAX_FAST': 0, # This implementation applies the straightforward
# softmax operation.
'CUDNN_SOFTMAX_ACCURATE': 1, # This implementation applies a scaling to the input
# to avoid any potential overflow.
'CUDNN_SOFTMAX_LOG' : 2 # This implementation applied the Log
# softmax operation, scaling the input to avoid any potential
# overflow.
}
# cudnnSoftmaxMode_t is used to select over which data the cudnnSoftmaxForward()
# and cudnnSoftmaxBackward() are computing their results.
cudnnSoftmaxMode = {
'CUDNN_SOFTMAX_MODE_INSTANCE': 0, # The softmax operation is computed per image (N)
# across the dimensions C,H,W.
'CUDNN_SOFTMAX_MODE_CHANNEL': 1 # The softmax operation is computed per spatial
# location (H,W) per image (N) across the dimension
# C.
}
# cudnnPoolingMode_t is an enumerated type passed to
# cudnnSetPoolingDescriptor() to select the pooling method to be used by
# cudnnPoolingForward() and cudnnPoolingBackward() .
cudnnPoolingMode = {
'CUDNN_POOLING_MAX': 0, # The maximum value inside the pooling window will
# be used.
'CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING': 1, # The values inside the
# pooling window will be averaged and this count
# includes padded values.
'CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING': 2, # The values inside the
# pooling window will be averaged and this count
# does not include padded values.
'CUDNN_POOLING_MAX_DETERMINISTIC': 3 # The maximum value inside the pooling
# window is used. The algorithm used is
# deterministic.
}
# cudnnActivationMode_t is an enumerated type used to select the neuron activation
# function used in cudnnActivationForward() and cudnnActivationBackward() .
cudnnActivationMode = {
'CUDNN_ACTIVATION_SIGMOID': 0, # sigmoid function
'CUDNN_ACTIVATION_RELU': 1, # rectified linear function
'CUDNN_ACTIVATION_TANH': 2, # hyperbolic tangent function
'CUDNN_ACTIVATION_CLIPPED_RELU': 3,
'CUDNN_ACTIVATION_ELU': 4
}
# cudnnNanPropagation_t is an enumerated type to specify the propogation of Nan
cudnnNanPropagation = {
'CUDNN_NOT_PROPAGATE_NAN': 0,
'CUDNN_PROPAGATE_NAN': 1
}
def cudnnCheckStatus(status):
"""
Raise cuDNN exception
Raise an exception corresponding to the specified cuDNN error code.
Parameters
----------
status : int
cuDNN error code
"""
if status != 0:
raise cudnnError(status)
# Helper functions
_libcudnn.cudnnGetVersion.restype = ctypes.c_size_t
_libcudnn.cudnnGetVersion.argtypes = []
def cudnnGetVersion():
"""
Get cuDNN Version.
"""
return _libcudnn.cudnnGetVersion()
_libcudnn.cudnnCreate.restype = int
_libcudnn.cudnnCreate.argtypes = [ctypes.c_void_p]
def cudnnCreate():
"""
Initialize cuDNN.
Initializes cuDNN and returns a handle to the cuDNN context.
Returns
-------
handle : cudnnHandle
cuDNN context
"""
handle = ctypes.c_void_p()
status = _libcudnn.cudnnCreate(ctypes.byref(handle))
cudnnCheckStatus(status)
return handle.value
_libcudnn.cudnnDestroy.restype = int
_libcudnn.cudnnDestroy.argtypes = [ctypes.c_void_p]
def cudnnDestroy(handle):
"""
Release cuDNN resources.
Release hardware resources used by cuDNN.
Parameters
----------
handle : cudnnHandle
cuDNN context.
"""
status = _libcudnn.cudnnDestroy(ctypes.c_void_p(handle))
cudnnCheckStatus(status)
_libcudnn.cudnnSetStream.restype = int
_libcudnn.cudnnSetStream.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
def cudnnSetStream(handle, id):
"""
Set current cuDNN library stream.
Parameters
----------
handle : cudnnHandle
cuDNN context.
id : cudaStream
Stream Id.
"""
status = _libcudnn.cudnnSetStream(handle, id)
cudnnCheckStatus(status)
_libcudnn.cudnnGetStream.restype = int
_libcudnn.cudnnGetStream.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
def cudnnGetStream(handle):
"""
Get current cuDNN library stream.
Parameters
----------
handle : int
cuDNN context.
Returns
-------
id : int
Stream ID.
"""
id = ctypes.c_void_p()
status = _libcudnn.cudnnGetStream(handle, ctypes.byref(id))
cudnnCheckStatus(status)
return id.value
_libcudnn.cudnnCreateTensorDescriptor.restype = int
_libcudnn.cudnnCreateTensorDescriptor.argtypes = [ctypes.c_void_p]
def cudnnCreateTensorDescriptor():
"""
Create a Tensor descriptor object.
Allocates a cudnnTensorDescriptor_t structure and returns a pointer to it.
Returns
-------
tensor_descriptor : int
Tensor descriptor.
"""
tensor = ctypes.c_void_p()
status = _libcudnn.cudnnCreateTensorDescriptor(ctypes.byref(tensor))
cudnnCheckStatus(status)
return tensor.value
_libcudnn.cudnnSetTensor4dDescriptor.restype = int
_libcudnn.cudnnSetTensor4dDescriptor.argtypes = [ctypes.c_void_p, ctypes.c_int,
ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int,
ctypes.c_int]
def cudnnSetTensor4dDescriptor(tensorDesc, format, dataType, n, c, h, w):
"""
Initialize a previously created Tensor 4D object.
This function initializes a previously created Tensor4D descriptor object. The strides of
the four dimensions are inferred from the format parameter and set in such a way that
the data is contiguous in memory with no padding between dimensions.
Parameters
----------
tensorDesc : cudnnTensorDescriptor
Handle to a previously created tensor descriptor.
format : cudnnTensorFormat
Type of format.
dataType : cudnnDataType
Data type.
n : int
Number of images.
c : int
Number of feature maps per image.
h : int
Height of each feature map.
w : int
Width of each feature map.
"""
status = _libcudnn.cudnnSetTensor4dDescriptor(tensorDesc, format, dataType,
n, c, h, w)
cudnnCheckStatus(status)
_libcudnn.cudnnSetTensor4dDescriptorEx.restype = int
_libcudnn.cudnnSetTensor4dDescriptorEx.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, ]
def cudnnSetTensor4dDescriptorEx(tensorDesc, dataType, n, c, h, w, nStride, cStride, hStride, wStride):
""""
Initialize a Tensor descriptor object with strides.
This function initializes a previously created generic Tensor descriptor object into a
4D tensor, similarly to cudnnSetTensor4dDescriptor but with the strides explicitly
passed as parameters. This can be used to lay out the 4D tensor in any order or simply to
define gaps between dimensions.
Parameters
----------
tensorDesc : cudnnTensorDescriptor_t
Handle to a previously created tensor descriptor.
dataType : cudnnDataType
Data type.
n : int
Number of images.
c : int
Number of feature maps per image.
h : int
Height of each feature map.
w : int
Width of each feature map.
nStride : int
Stride between two consective images.
cStride : int
Stride between two consecutive feature maps.
hStride : int
Stride between two consecutive rows.
wStride : int
Stride between two consecutive columns.
"""
status = _libcudnn.cudnnSetTensor4dDescriptorEx(tensorDesc, dataType, n, c, h, w,
nStride, cStride, hStride, wStride)
cudnnCheckStatus(status)
_libcudnn.cudnnGetTensor4dDescriptor.restype = int
_libcudnn.cudnnGetTensor4dDescriptor.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ]
def cudnnGetTensor4dDescriptor(tensorDesc):
""""
Get parameters of a Tensor descriptor object.
This function queries the parameters of the previouly initialized Tensor4D descriptor
object.
Parameters
----------
tensorDesc : cudnnTensorDescriptor
Handle to a previously initialized tensor descriptor.
Returns
-------
dataType : cudnnDataType
Data type.
n : int
Number of images.
c : int
Number of feature maps per image.
h : int
Height of each feature map.
w : int
Width of each feature map.
nStride : int
Stride between two consective images.
cStride : int
Stride between two consecutive feature maps.
hStride : int
Stride between two consecutive rows.
wStride : int
Stride between two consecutive columns.
"""
dataType = ctypes.c_int()
n = ctypes.c_int()
c = ctypes.c_int()
h = ctypes.c_int()
w = ctypes.c_int()
nStride = ctypes.c_int()
cStride = ctypes.c_int()
hStride = ctypes.c_int()
wStride = ctypes.c_int()
status = _libcudnn.cudnnGetTensor4dDescriptor(tensorDesc, ctypes.byref(dataType), ctypes.byref(n),
ctypes.byref(c), ctypes.byref(h), ctypes.byref(w),
ctypes.byref(nStride), ctypes.byref(cStride),
ctypes.byref(hStride), ctypes.byref(wStride))
cudnnCheckStatus(status)
return dataType.value, n.value, c.value, h.value, w.value, nStride.value, cStride.value, \
hStride.value, wStride.value
_libcudnn.cudnnDestroyTensorDescriptor.restype = int
_libcudnn.cudnnDestroyTensorDescriptor.argtypes = [ctypes.c_void_p]
def cudnnDestroyTensorDescriptor(tensorDesc):
""""
Destroy a Tensor descriptor.
This function destroys a previously created Tensor descriptor object.
Parameters
----------
tensorDesc : cudnnTensorDescriptor
Previously allocated Tensor descriptor object.
"""
status = _libcudnn.cudnnDestroyTensorDescriptor(tensorDesc)
cudnnCheckStatus(status)
_libcudnn.cudnnTransformTensor.restype = int
_libcudnn.cudnnTransformTensor.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p]
def cudnnTransformTensor(handle, alpha, srcDesc, srcData, beta, destDesc, destData):
""""
Tensor layout conversion helper (dest = alpha * src + beta * dest).
This function copies the scaled data from one tensor to another tensor with a different
layout. Those descriptors need to have the same dimensions but not necessarily the
same strides. The input and output tensors must not overlap in any way (i.e., tensors
cannot be transformed in place). This function can be used to convert a tensor with an
unsupported format to a supported one.
Parameters
----------
handle : cudnnHandle
cuDNN context.
alpha : float
Scalar factor to be applied to every element of the input tensor before it is added
to the output tensor.
srcDesc : cudnnTensorDescriptor
Handle to a previously initialized tensor descriptor.
srcData : void_p
Pointer to data of the tensor described by srcDesc descriptor.
beta: float
Scaling factor which is applied on every element of the output tensor prior to adding
the result of the operation. Note that if beta is zero, the output is not read and can
contain any uninitialized data (including Nan numbers).
destDesc : cudnnTensorDescriptor
Handle to a previously initialized tensor descriptor.
destData : void_p
Pointer to data of the tensor described by destDesc descriptor.
"""
dataType, _, _, _, _, _, _, _, _ = cudnnGetTensor4dDescriptor(destDesc)
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
betaRef = ctypes.byref(ctypes.c_double(beta))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
betaRef = ctypes.byref(ctypes.c_float(beta))
status = _libcudnn.cudnnTransformTensor(handle, alphaRef, srcDesc,
srcData, betaRef,
destDesc, destData)
cudnnCheckStatus(status)
_libcudnn.cudnnAddTensor.restype = int
_libcudnn.cudnnAddTensor.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p]
def cudnnAddTensor(handle, alpha, biasDesc, biasData, beta, srcDestDesc, srcDestData):
""""
Tensor Bias addition : srcDest = alpha * bias + beta * srcDestDesc.
This function adds the scaled values of one tensor to another tensor. The amount
of data described by the biasDesc descriptor must match exactly the amount of data
needed to perform the addition.
Parameters
----------
handle : cudnnHandle
Handle to a cuDNN context.
alpha : float
Scalar factor to be applied to every data element of the bias tensor before it is added
to the output tensor.
biasDesc : cudnnTensorDescriptor
Handle to a previoulsy initialized tensor descriptor.
biasData : void_p
Pointer to data of the tensor described by biasDesc.
beta: float
Scaling factor which is applied on every element of the output tensor prior to adding
the result of the operation. Note that if beta is zero, the output is not read and can
contain any uninitialized data (including Nan numbers).
srcDestDesc : cudnnTensorDescriptor
Handle to a previoulsy initialized tensor descriptor.
srcDestData : void_p
Pointer to data of the tensor described by srcDestDesc.
"""
dataType, _, _, _, _, _, _, _, _ = cudnnGetTensor4dDescriptor(srcDestDesc)
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
betaRef = ctypes.byref(ctypes.c_double(beta))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
betaRef = ctypes.byref(ctypes.c_float(beta))
status = _libcudnn.cudnnAddTensor(handle, alphaRef, biasDesc,
biasData, betaRef,
srcDestDesc, srcDestData)
cudnnCheckStatus(status)
_libcudnn.cudnnSetTensor.restype = int
_libcudnn.cudnnSetTensor.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p]
def cudnnSetTensor(handle, srcDesc, srcData, value):
""""
Set all data points of a tensor to a given value : srcDest = alpha.
Parameters
----------
handle : cudnnHandle
Handle to a previously created cuDNN context.
srcDesc : cudnnTensorDescriptor
Handle to a previously initialized tensor descriptor.
srcData : void_p
Pointer to data of the tensor described by srcDesc descriptor.
value : float
Value that all elements of the tensor will be set to.
"""
dataType, _, _, _, _, _, _, _, _ = cudnnGetTensor4dDescriptor(srcDesc)
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
status = _libcudnn.cudnnSetTensor(handle, srcDesc, srcData, alphaRef)
cudnnCheckStatus(status)
_libcudnn.cudnnScaleTensor.restype = int
_libcudnn.cudnnScaleTensor.argtypes = [ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p]
def cudnnScaleTensor(handle, srcDesc, srcData, alpha):
""""
This function scales all the elements of a tensor by a give factor.
Set all data points of a tensor to scaled value : srcDest = alpha * srcDest.
Parameters
----------
handle : cudnnHandle
Handle to a previously created cuDNN context.
srcDesc : cudnnTensorDescriptor
Handle to a previously initialized tensor descriptor.
srcData : void_p
Pointer to data of the tensor described by srcDesc descriptor.
alpha : float
Value that all elements of the tensor will be scaled with.
"""
dataType, _, _, _, _, _, _, _, _ = cudnnGetTensor4dDescriptor(srcDesc)
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
status = _libcudnn.cudnnScaleTensor(handle, srcDesc, srcData, alphaRef)
cudnnCheckStatus(status)
_libcudnn.cudnnCreateFilterDescriptor.restype = int
_libcudnn.cudnnCreateFilterDescriptor.argtypes = [ctypes.c_void_p]
def cudnnCreateFilterDescriptor():
""""
Create a filter descriptor.
This function creates a filter descriptor object by allocating the memory needed
to hold its opaque structure.
Parameters
----------
Returns
-------
wDesc : cudnnFilterDescriptor
Handle to a newly allocated filter descriptor.
"""
wDesc = ctypes.c_void_p()
status = _libcudnn.cudnnCreateFilterDescriptor(ctypes.byref(wDesc))
cudnnCheckStatus(status)
return wDesc.value
_libcudnn.cudnnSetFilter4dDescriptor.restype = int
_libcudnn.cudnnSetFilter4dDescriptor.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_int]
def cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w):
""""
Initialize a filter descriptor.
This function initializes a previously created filter descriptor object into a 4D filter.
Filters layout must be contiguous in memory.
Parameters
----------
wDesc : cudnnFilterDescriptor
Handle to a previously created filter descriptor.
dataType : cudnnDataType
Data type.
format: cudnnTensorFormat
Tensor format
k : int
Number of output feature maps.
c : int
Number of input feature maps.
h : int
Height of each filter.
w : int
Width of each filter.
"""
status = _libcudnn.cudnnSetFilter4dDescriptor(wDesc, dataType, format, k, c, h, w)
cudnnCheckStatus(status)
_libcudnn.cudnnGetFilter4dDescriptor.restype = int
_libcudnn.cudnnGetFilter4dDescriptor.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p]
def cudnnGetFilter4dDescriptor(wDesc):
""""
Get parameters of filter descriptor.
This function queries the parameters of the previouly initialized filter descriptor object.
Parameters
----------
wDesc : cudnnFilterDescriptor
Handle to a previously created filter descriptor.
Returns
-------
dataType : cudnnDataType
Data type.
format: cudnnTensorFormat
Tensor format
k : int
Number of output feature maps.
c : int
Number of input feature maps.
h : int
Height of each filter.
w : int
Width of each filter.
"""
dataType = ctypes.c_int()
format = ctypes.c_int()
k = ctypes.c_int()
c = ctypes.c_int()
h = ctypes.c_int()
w = ctypes.c_int()
status = _libcudnn.cudnnGetFilter4dDescriptor(wDesc, ctypes.byref(dataType),
ctypes.byref(format),
ctypes.byref(k), ctypes.byref(c),
ctypes.byref(h), ctypes.byref(w))
cudnnCheckStatus(status)
return dataType.value, format.value, k.value, c.value, h.value, w.value
_libcudnn.cudnnDestroyFilterDescriptor.restype = int
_libcudnn.cudnnDestroyFilterDescriptor.argtypes = [ctypes.c_void_p]
def cudnnDestroyFilterDescriptor(wDesc):
""""
Destroy filter descriptor.
This function destroys a previously created Tensor4D descriptor object.
Parameters
----------
wDesc : cudnnFilterDescriptor
"""
status = _libcudnn.cudnnDestroyFilterDescriptor(wDesc)
cudnnCheckStatus(status)
_libcudnn.cudnnCreateConvolutionDescriptor.restype = int
_libcudnn.cudnnCreateConvolutionDescriptor.argtypes = [ctypes.c_void_p]
def cudnnCreateConvolutionDescriptor():
""""
Create a convolution descriptor.
This function creates a convolution descriptor object by allocating the memory needed to
hold its opaque structure.
Returns
-------
convDesc : cudnnConvolutionDescriptor
Handle to newly allocated convolution descriptor.
"""
convDesc = ctypes.c_void_p()
status = _libcudnn.cudnnCreateConvolutionDescriptor(ctypes.byref(convDesc))
cudnnCheckStatus(status)
return convDesc.value
_libcudnn.cudnnSetConvolution2dDescriptor.restype = int
_libcudnn.cudnnSetConvolution2dDescriptor.argtypes = [ctypes.c_void_p, ctypes.c_int,
ctypes.c_int, ctypes.c_int, ctypes.c_int,
ctypes.c_int, ctypes.c_int, ctypes.c_int]
def cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v, dilation_h, dilation_w, mode,
computeType):
""""
Initialize a convolution descriptor.
This function initializes a previously created convolution descriptor object into a 2D
correlation. This function assumes that the tensor and filter descriptors corresponds
to the formard convolution path and checks if their settings are valid. That same
convolution descriptor can be reused in the backward path provided it corresponds to
the same layer.
Parameters
----------
convDesc : cudnnConvolutionDescriptor
Handle to a previously created convolution descriptor.
pad_h : int
zero-padding height: number of rows of zeros implicitly concatenated
onto the top and onto the bottom of input images.
pad_w : int
zero-padding width: number of columns of zeros implicitly concatenated
onto the left and onto the right of input images.
u : int
Vertical filter stride.
v : int
Horizontal filter stride.
dilation_h : int
Filter height dilation.
dilation_w : int
Filter width dilation.
mode : cudnnConvolutionMode
Select between CUDNN_CONVOLUTION or CUDNN_CROSS_CORRELATION.
computeType : cudnnDataType
Compute precision
"""
status = _libcudnn.cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v,
dilation_h, dilation_w, mode,
computeType)
cudnnCheckStatus(status)
_libcudnn.cudnnGetConvolution2dDescriptor.restype = int
_libcudnn.cudnnGetConvolution2dDescriptor.argtypes = [ctypes.c_void_p]
def cudnnGetConvolution2dDescriptor(convDesc):
""""
Get a convolution descriptor.
This function queries a previously initialized 2D convolution descriptor object.
Parameters
----------
convDesc : cudnnConvolutionDescriptor
Handle to a previously created convolution descriptor.
Returns
-------
pad_h : int
zero-padding height: number of rows of zeros implicitly concatenated onto
the top and onto the bottom of input images.
pad_w : int
zero-padding width: number of columns of zeros implicitly concatenated
onto the left and onto the right of input images.
u : int
Vertical filter stride.
v : int
Horizontal filter stride.
dilation_h : int
Filter height dilation.
dilation_w : int
Filter width dilation.
mode : cudnnConvolutionMode
Either CUDNN_CONVOLUTION or CUDNN_CROSS_CORRELATION.
computeType : cudnnDataType
Compute precision
"""
pad_h = ctypes.c_int()
pad_w = ctypes.c_int()
u = ctypes.c_int()
v = ctypes.c_int()
dilation_h = ctypes.c_int()
dilation_w = ctypes.c_int()
mode = ctypes.c_int()
computeType = ctypes.c_int()
status = _libcudnn.cudnnGetConvolution2dDescriptor(convDesc, ctypes.byref(pad_h),
ctypes.byref(pad_w), ctypes.byref(u),
ctypes.byref(v), ctypes.byref(dilation_h),
ctypes.byref(dilation_w),
ctypes.byref(mode), ctypes.byref(computeType))
cudnnCheckStatus(status)
return (pad_h.value, pad_w.value, u.value, v.value, upscalex.value, upscaley.value, mode.value,
computeType.value)
_libcudnn.cudnnGetConvolution2dForwardOutputDim.restype = int
_libcudnn.cudnnGetConvolution2dForwardOutputDim.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, wDesc):
""""
Return the dimensions of the output tensor given a convolution descriptor.
This function returns the dimensions of the resulting 4D tensor of a 2D
convolution, given the convolution descriptor, the input tensor descriptor and
the filter descriptor. This function can help to setup the output tensor and allocate
the proper amount of memory prior to launching the actual convolution.
Parameters
----------
convDesc : cudnnConvolutionDescriptor
Handle to a previously created convolution descriptor.
inputTensorDesc: cudnnTensorDescriptor
Handle to a previously initialized tensor descriptor.
wDesc: cudnnFilterDescriptor
Handle to a previously initialized filter descriptor.
Returns
-------
n : int
Number of output images.
c : int
Number of output feature maps per image.
h : int
Height of each output feature map.
w : int
Width of each output feature map.
"""
n = ctypes.c_int()
c = ctypes.c_int()
h = ctypes.c_int()
w = ctypes.c_int()
status = _libcudnn.cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc,
wDesc, ctypes.byref(n),
ctypes.byref(c), ctypes.byref(h),
ctypes.byref(w))
cudnnCheckStatus(status)
return n.value, c.value, h.value, w.value
_libcudnn.cudnnSetConvolutionNdDescriptor.restype = int
_libcudnn.cudnnSetConvolutionNdDescriptor.argtypes = [ctypes.c_void_p, # convDesc
ctypes.c_int, # arrayLength
ctypes.POINTER(ctypes.c_int), # padA[]
ctypes.POINTER(ctypes.c_int), # filterStrideA[]
ctypes.POINTER(ctypes.c_int), # dilationA[]
ctypes.c_int, # mode
ctypes.c_int] # dataType
def cudnnSetConvolutionNdDescriptor(convDesc, padA, filterStrideA, dilationA, mode, dataType):
dim = len(padA)
status = _libcudnn.cudnnSetConvolutionNdDescriptor(convDesc,
dim,
(ctypes.c_int * dim)(*padA),
(ctypes.c_int*dim)(*filterStrideA),
(ctypes.c_int*dim)(*dilationA),
mode,
dataType)
cudnnCheckStatus(status)
_libcudnn.cudnnDestroyConvolutionDescriptor.restype = int
_libcudnn.cudnnDestroyConvolutionDescriptor.argtypes = [ctypes.c_void_p]
def cudnnDestroyConvolutionDescriptor(convDesc):
""""
Destroy a convolution descriptor.
This function destroys a previously created convolution descriptor object.
Parameters
----------
convDesc : int
Previously created convolution descriptor.
"""