/
dnn.py
3461 lines (2865 loc) · 131 KB
/
dnn.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
from __future__ import absolute_import, print_function, division
import ctypes
import os
import sys
import warnings
import numpy as np
from six import integer_types
from six.moves import reduce
import theano
from theano import Op, Apply, tensor, config, Variable
from theano.scalar import (as_scalar, constant, Log, get_scalar_type,
int32 as int_t, bool as bool_t, uint32 as uint32_t)
from theano.tensor import as_tensor_variable, Argmax
from theano.gradient import DisconnectedType, grad_not_implemented
from theano.gof import Optimizer, local_optimizer, COp, ParamsType, EnumList
from theano.gof.cmodule import GCC_compiler
from theano.gof.type import CDataType, Generic
from theano.compile import optdb
from theano.compile.ops import shape_i, shape_i_op
from theano.tensor.nnet import LogSoftmax, SoftmaxGrad
from theano.tensor.nnet.abstract_conv import (AbstractConv2d,
AbstractConv2d_gradWeights,
AbstractConv2d_gradInputs,
AbstractConv3d,
AbstractConv3d_gradWeights,
AbstractConv3d_gradInputs,
get_conv_output_shape,
assert_conv_shape)
from theano.tensor.signal.pool import (
Pool, MaxPoolGrad, AveragePoolGrad)
from . import pygpu, cudnn_defs
from .type import (get_context, gpu_context_type, list_contexts,
GpuArraySharedVariable)
from .basic_ops import (as_gpuarray_variable, infer_context_name, gpuarray_helper_inc_dir,
gpu_contiguous, GpuAllocEmpty,
empty_like, GpuArrayType, HostFromGpu)
from .elemwise import GpuElemwise, GpuCAReduceCuda
from .reduction import GpuMaxAndArgmax
# These don't exist in gpuarray
# GpuDownsampleFactorMax, GpuDownsampleFactorMaxGrad
from .nnet import GpuSoftmax
from .opt import (gpu_seqopt, register_opt, pool_db, pool_db2,
op_lifter, register_opt2, register_inplace)
from .opt_util import alpha_merge, output_merge, inplace_allocempty, pad_dims, unpad_dims
from theano.configdefaults import SUPPORTED_DNN_CONV_ALGO_RUNTIME
DNN_CONV_ALGO_CHOOSE_ONCE = ['guess_once', 'time_once']
DNN_CONV_ALGO_CHOOSE_TIME = ['time_once', 'time_on_shape_change']
try:
from pygpu import gpuarray
except ImportError:
pass
# Update these names when new versions of cudnn are supported.
WIN32_CUDNN_NAMES = ['cudnn64_6.dll', 'cudnn64_5.dll']
def _load_lib(name):
try:
return ctypes.cdll.LoadLibrary(name)
except OSError:
return None
def _dnn_lib():
if _dnn_lib.handle is None:
import ctypes.util
if config.dnn.bin_path != "":
if sys.platform == 'darwin':
dnn_handle = _load_lib(os.path.join(config.dnn.bin_path, 'libcudnn.dylib'))
elif sys.platform == 'win32':
for name in WIN32_CUDNN_NAMES:
dnn_handle = _load_lib(os.path.join(config.dnn.bin_path, name))
if dnn_handle is not None:
break
else:
dnn_handle = _load_lib(os.path.join(config.dnn.bin_path, 'libcudnn.so'))
else:
lib_name = ctypes.util.find_library('cudnn')
if lib_name is None and sys.platform == 'win32':
for name in WIN32_CUDNN_NAMES:
lib_name = ctypes.util.find_library(name)
if lib_name:
break
if lib_name is None:
raise RuntimeError('Could not find cudnn library (looked for v5* or v6*)')
else:
dnn_handle = ctypes.cdll.LoadLibrary(lib_name)
if dnn_handle is None:
raise RuntimeError('Could not load cudnn library')
_dnn_lib.handle = dnn_handle
cudnn = _dnn_lib.handle
cudnn.cudnnCreate.argtypes = [ctypes.POINTER(ctypes.c_void_p)]
cudnn.cudnnCreate.restype = ctypes.c_int
cudnn.cudnnDestroy.argtypes = [ctypes.c_void_p]
cudnn.cudnnDestroy.restype = ctypes.c_int
return _dnn_lib.handle
_dnn_lib.handle = None
def _make_handle(ctx):
cudnn = _dnn_lib()
handle = ctypes.c_void_p()
with ctx:
err = cudnn.cudnnCreate(ctypes.byref(handle))
if err != 0:
raise RuntimeError("error creating cudnn handle")
return handle
def _dnn_check_compile():
preambule = """
#include <stdio.h>
#include <cudnn.h>
#include <cudnn_helper.h>
"""
# No need for the context in here since we won't execute that code
body = """
cudnnHandle_t _handle = NULL;
cudnnStatus_t err;
if ((err = cudnnCreate(&_handle)) != CUDNN_STATUS_SUCCESS) {
fprintf(stderr, "could not create cuDNN handle: %s",
cudnnGetErrorString(err));
return 1;
}
"""
path_wrapper = "\"" if os.name == 'nt' else ""
params = ["-l", "cudnn"]
params.extend(['-I%s%s%s' % (path_wrapper, gpuarray_helper_inc_dir(), path_wrapper)])
if config.dnn.include_path:
params.extend(['-I%s%s%s' % (path_wrapper, config.dnn.include_path, path_wrapper)])
if config.cuda.include_path:
params.extend(['-I%s%s%s' % (path_wrapper, config.cuda.include_path, path_wrapper)])
if config.dnn.library_path:
params.extend(['-L%s%s%s' % (path_wrapper, config.dnn.library_path, path_wrapper)])
# Do not run here the test program. It would run on the
# default gpu, not the one selected by the user. If mixed
# GPU are installed or if the GPUs are configured in
# exclusive mode, this cause bad detection.
# NB: GCC_compiler.try_flags() may return just a boolean instead of a tuple (avail, out, here).
compiler_res = GCC_compiler.try_flags(
params, preambule=preambule, body=body,
try_run=False, output=True)
avail, out, err = compiler_res if isinstance(compiler_res, tuple) else (compiler_res, None, None)
if not avail:
return False, ("cannot compile with cuDNN. "
"We got this error:\n" + str(err))
return True, None
def _dnn_check_version():
v = version()
if v < 5000:
return False, "cuDNN version is too old. Update to v5* or higher, was %d." % v
if v >= 6100:
warnings.warn("Your cuDNN version is more recent than "
"Theano. If you encounter problems, try "
"updating Theano or downgrading cuDNN to "
"a version >= v5 and <= v6.")
return True, None
def dnn_present():
if dnn_present.avail is not None:
return dnn_present.avail
if config.dnn.enabled == "False":
dnn_present.msg = "Disabled by dnn.enabled flag"
dnn_present.avail = False
return False
if pygpu is None:
dnn_present.msg = "PyGPU not available"
dnn_present.avail = False
return False
if config.dnn.enabled == "no_check":
dnn_present.avail, dnn_present.msg = True, "presence check disabled by dnn.enabled flag"
else:
dnn_present.avail, dnn_present.msg = _dnn_check_compile()
if dnn_present.avail:
dnn_present.avail, dnn_present.msg = _dnn_check_version()
if not dnn_present.avail:
return False
return dnn_present.avail
dnn_present.avail = None
dnn_present.msg = None
def dnn_available(context_name):
if not dnn_present():
dnn_available.msg = dnn_present.msg
return False
ctx = get_context(context_name)
if not ctx.kind == b'cuda':
dnn_available.msg = "Not on a CUDA device."
return False
# This is a hack because bin_id is in the from of
# "<something>_<major><minor>" for cuda devices.
if ctx.bin_id[-2:] < b'30':
dnn_available.msg = "Device not supported"
return False
return True
dnn_available.msg = None
def CUDNNDataType(name, freefunc=None):
cargs = []
if config.dnn.bin_path:
if sys.platform == 'darwin':
cargs.append('-Wl,-rpath,' + config.dnn.bin_path)
else:
cargs.append('-Wl,-rpath,"' + config.dnn.bin_path + '"')
return CDataType(name, freefunc,
headers=['cudnn.h'],
header_dirs=[config.dnn.include_path,
config.cuda.include_path],
libraries=['cudnn'],
lib_dirs=[config.dnn.library_path],
compile_args=cargs,
version=version(raises=False))
class DnnVersion(Op):
__props__ = ()
def c_headers(self):
return ['cudnn.h']
def c_header_dirs(self):
return [config.dnn.include_path, config.cuda.include_path]
def c_libraries(self):
return ['cudnn']
def c_lib_dirs(self):
return [config.dnn.library_path]
def c_compile_args(self):
if config.dnn.bin_path:
if sys.platform == 'darwin':
return ['-Wl,-rpath,' + config.dnn.bin_path]
else:
return ['-Wl,-rpath,"' + config.dnn.bin_path + '"']
return []
def c_support_code(self):
return """
#if PY_MAJOR_VERSION >= 3
#define PyInt_FromLong PyLong_FromLong
#endif
"""
def make_node(self):
return Apply(self, [], [Generic()()])
def c_code(self, node, name, inputs, outputs, sub):
o = outputs[0]
return """
%(o)s = PyTuple_Pack(2, PyInt_FromLong(CUDNN_VERSION), PyInt_FromLong(cudnnGetVersion()));
""" % locals()
def do_constant_folding(self, node):
# Needed as we do not want to cache this information.
return False
def c_code_cache_version(self):
# Not needed, but make it clear that we do not want to cache this.
return None
def version(raises=True):
"""Return the current cuDNN version we link with.
This also does a check that the header version matches the runtime version.
:raises: If True, raise an exception if cuDNN is not present.
Otherwise, return -1.
It always raise an RuntimeError if the header and library version
are not the same.
"""
if not dnn_present():
if raises:
raise RuntimeError(
"We can't determine the cudnn version as it is not available",
dnn_available.msg)
else:
return -1
if version.v is None:
f = theano.function([], DnnVersion()(),
theano.Mode(optimizer=None),
profile=False)
v = f()
if v[0] != v[1]:
raise RuntimeError("Mixed dnn version. The header is version %s "
"while the library is version %s." % v)
version.v = v[1]
return version.v
version.v = None
handle_type = CUDNNDataType('cudnnHandle_t', 'cudnnDestroy')
# Get cuDNN definitions to be used.
cudnn = cudnn_defs.get_definitions(version(raises=False))
def get_precision(precision, inputs):
if precision is None:
precision = theano.config.dnn.conv.precision
if precision == 'as_input' or precision == 'as_input_f32':
nprec = theano.scalar.upcast(*[i.dtype for i in inputs])
if nprec == 'float16' and precision == 'as_input_f32':
precision = 'float32'
else:
precision = nprec
return precision
class DnnBase(COp):
"""
Creates a handle for cudnn and pulls in the cudnn libraries and headers.
"""
# dnn does not know about broadcasting, so we do not need to assert
# the input broadcasting pattern.
check_broadcast = False
params_type = handle_type
def dnn_context(self, node):
return node.outputs[0].type.context_name
def get_params(self, node):
ctx_name = self.dnn_context(node)
ctx = get_context(ctx_name)
if not hasattr(ctx, 'cudnn_handle_param'):
ptr = ctx.cudnn_handle.value
res = handle_type.make_value(ptr)
ctx.cudnn_handle_param = res
if isinstance(self.params_type, ParamsType):
if not self.params_type.has_type(handle_type):
raise TypeError('DnnBase: params_type must take into account the cuDNN handle type.')
handle_field = self.params_type.get_field(handle_type)
return self.params_type.get_params(self, **{handle_field: ctx.cudnn_handle_param})
return ctx.cudnn_handle_param
def __init__(self, files=None, c_func=None):
if files is None:
files = []
COp.__init__(self, ["c_code/dnn_base.c"] + files, c_func)
def c_headers(self):
return ['gpuarray/types.h', 'gpuarray/array.h', 'gpuarray/kernel.h',
'gpuarray/util.h', 'gpuarray/ext_cuda.h', 'gpuarray_api.h',
'numpy_compat.h', 'cudnn.h', 'cudnn_helper.h',
'gpuarray_helper.h']
def c_header_dirs(self):
return [gpuarray_helper_inc_dir(), pygpu.get_include(),
config.dnn.include_path, config.cuda.include_path]
def c_libraries(self):
return ['cudnn', 'gpuarray']
def c_lib_dirs(self):
return [config.dnn.library_path]
def c_compile_args(self):
if config.dnn.bin_path:
if sys.platform == 'darwin':
return ['-Wl,-rpath,' + config.dnn.bin_path]
else:
return ['-Wl,-rpath,"' + config.dnn.bin_path + '"']
return []
def c_code_cache_version(self):
return (super(DnnBase, self).c_code_cache_version(), version(), 1)
class GpuDnnConvDesc(COp):
"""
This Op builds a convolution descriptor for use in the other convolution
operations.
See the doc of :func:`dnn_conv` for a description of the parameters
"""
__props__ = ('border_mode', 'subsample', 'dilation', 'conv_mode', 'precision')
params_type = ParamsType(pad0=int_t, pad1=int_t, pad2=int_t,
sub0=int_t, sub1=int_t, sub2=int_t,
dil0=int_t, dil1=int_t, dil2=int_t,
nb_dims=int_t,
bmode=EnumList(('BORDER_MODE_FULL', 'full'),
('BORDER_MODE_VALID', 'valid'),
('BORDER_MODE_HALF', 'half')),
conv_mode=cudnn.cudnnConvolutionMode_t,
precision=cudnn.cudnnDataType_t)
def c_headers(self):
return ['cudnn.h', 'cudnn_helper.h']
def c_header_dirs(self):
return [gpuarray_helper_inc_dir(), config.dnn.include_path,
config.cuda.include_path]
def c_libraries(self):
return ['cudnn']
def c_lib_dirs(self):
return [config.dnn.library_path]
def c_compile_args(self):
if config.dnn.bin_path:
if sys.platform == 'darwin':
return ['-Wl,-rpath,' + config.dnn.bin_path]
else:
return ['-Wl,-rpath,"' + config.dnn.bin_path + '"']
return []
def do_constant_folding(self, node):
return False
def __init__(self, border_mode, subsample=(1, 1), dilation=(1, 1), conv_mode='conv',
precision="float32"):
COp.__init__(self, ["c_code/conv_desc.c"], "APPLY_SPECIFIC(conv_desc)")
if version() < 6000 and any([d != 1 for d in dilation]):
raise RuntimeError("Dilation > 1 not supported for cuDNN version < 6.")
if isinstance(border_mode, integer_types):
border_mode = (border_mode,) * len(subsample)
if isinstance(border_mode, tuple):
assert len(border_mode) == len(subsample)
border_mode = tuple(map(int, border_mode))
if not ((isinstance(border_mode, tuple) and min(border_mode) >= 0) or
border_mode in ('valid', 'full', 'half')):
raise ValueError(
'invalid border_mode {}, which must be either '
'"valid", "full", "half", an integer or a pair of'
' integers'.format(border_mode))
self.border_mode = border_mode
assert len(subsample) in (2, 3)
self.subsample = subsample
assert cudnn.cudnnConvolutionMode_t.has_alias(conv_mode)
self.conv_mode = conv_mode
assert len(dilation) == len(subsample)
self.dilation = dilation
assert cudnn.cudnnDataType_t.has_alias(precision)
self.precision = precision
def make_node(self, kern_shape):
kern_shape = as_tensor_variable(kern_shape)
if kern_shape.type.ndim != 1 or kern_shape.dtype not in theano.tensor.basic.int_dtypes:
raise TypeError('kern must be an int64 1D shape tensor')
kern_shape = theano.tensor.basic.cast(kern_shape, 'int64')
node = Apply(self, [kern_shape],
[CUDNNDataType("cudnnConvolutionDescriptor_t",
freefunc="cudnnDestroyConvolutionDescriptor")()])
# DebugMode cannot compare the values of CDataType variables, so by
# default it returns False all the time. To prevent DebugMode from
# complaining because of the MergeOptimizer, we make this variable
# always compare to True.
out = node.outputs[0]
out.tag.values_eq_approx = tensor.type.values_eq_approx_always_true
return node
bmode = property(lambda self: 'valid' if isinstance(self.border_mode, tuple) else self.border_mode)
pad0 = property(lambda self: self.border_mode[0] if isinstance(self.border_mode, tuple) else 0)
pad1 = property(lambda self: self.border_mode[1] if isinstance(self.border_mode, tuple) else 0)
pad2 = property(lambda self: self.border_mode[2] if (isinstance(self.border_mode, tuple) and
len(self.border_mode) > 2) else 0)
sub0 = property(lambda self: self.subsample[0])
sub1 = property(lambda self: self.subsample[1])
sub2 = property(lambda self: self.subsample[2] if len(self.subsample) > 2 else 0)
dil0 = property(lambda self: self.dilation[0])
dil1 = property(lambda self: self.dilation[1])
dil2 = property(lambda self: self.dilation[2] if len(self.dilation) > 2 else 0)
nb_dims = property(lambda self: len(self.subsample))
def c_code_cache_version(self):
return (super(GpuDnnConvDesc, self).c_code_cache_version(), version())
def __setstate__(self, d):
self.__dict__.update(d)
if not hasattr(self, "dilation"):
self.dilation = (1,) * len(self.subsample)
# scalar constants
_zero = constant(np.asarray(0.0, dtype='float64'))
_one = constant(np.asarray(1.0, dtype='float64'))
def ensure_dt(val, default, name, dtype):
if dtype == 'float16':
dtype = 'float32'
if val is None:
val = default.clone()
if not isinstance(val, Variable):
val = constant(val)
if hasattr(val, 'ndim') and val.ndim == 0:
val = as_scalar(val)
if not isinstance(val.type, theano.scalar.Scalar):
raise TypeError("%s: expected a scalar value" % (name,))
if not val.type.dtype == dtype:
val = val.astype(dtype)
return val
class GpuDnnConv(DnnBase):
"""
The forward convolution.
Parameters
----------
image
kernel
descr :
The convolution descriptor.
algo : {'small', 'none', 'large', 'fft', 'fft_tiling', 'winograd', 'guess_once',
'guess_on_shape_change', 'time_once', 'time_on_shape_change'}
Default is the value of :attr:`config.dnn.conv.algo_fwd`.
num_groups :
Divides the image, kernel and output tensors into num_groups
separate groups. Each which carry out convolutions separately
"""
_f16_ok = True
__props__ = ('algo', 'inplace', 'num_groups')
check_input = False
params_type = ParamsType(conv_algo=cudnn.cudnnConvolutionFwdAlgo_t,
choose_algo=bool_t, choose_once=bool_t, choose_time=bool_t,
inplace=bool_t,
handle=handle_type,
num_groups=int_t)
def __init__(self, algo=None, inplace=False, num_groups=1):
DnnBase.__init__(self, ["c_code/dnn_conv_base.c", "c_code/dnn_fwd.c"],
"APPLY_SPECIFIC(conv_fwd)")
if algo is None:
algo = config.dnn.conv.algo_fwd
self.algo = algo
self.inplace = bool(inplace)
if self.inplace:
self.destroy_map = {0: [2]}
assert cudnn.cudnnConvolutionFwdAlgo_t.has_alias(self.algo) or self.algo in SUPPORTED_DNN_CONV_ALGO_RUNTIME
self.conv_algo = cudnn.cudnnConvolutionFwdAlgo_t.CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM
if self.algo not in SUPPORTED_DNN_CONV_ALGO_RUNTIME:
self.conv_algo = self.algo
self.choose_algo = self.algo in SUPPORTED_DNN_CONV_ALGO_RUNTIME
self.choose_once = self.algo in DNN_CONV_ALGO_CHOOSE_ONCE
self.choose_time = self.algo in DNN_CONV_ALGO_CHOOSE_TIME
self.num_groups = num_groups
def __setstate__(self, d):
self.__dict__.update(d)
if not hasattr(self, 'algo'):
if hasattr(self, 'workmem'):
self.algo = self.workmem
else:
self.algo = config.dnn.conv.algo_fwd
if not hasattr(self, 'inplace'):
self.inplace = False
if not hasattr(self, 'num_groups'):
self.num_groups = 1
def make_node(self, img, kern, output, desc, alpha=None, beta=None):
ctx_name = infer_context_name(img, kern, output)
img = as_gpuarray_variable(img, ctx_name)
kern = as_gpuarray_variable(kern, ctx_name)
output = as_gpuarray_variable(output, ctx_name)
if img.type.ndim not in (4, 5):
raise TypeError('img must be 4D or 5D tensor')
if kern.type.ndim not in (4, 5):
raise TypeError('kern must be 4D or 5D tensor')
if output.type.ndim not in (4, 5):
raise TypeError('output must be a 4D or 5D tensor')
if (img.type.ndim != kern.type.ndim or
img.type.ndim != output.type.ndim):
raise TypeError("The number of dimensions of "
"img, kern and output must match")
if img.type.ndim == 5 and self.algo not in (cudnn.conv3d_fwd_algorithms +
SUPPORTED_DNN_CONV_ALGO_RUNTIME):
raise ValueError("convolution algo %s can't be used for "
"3d convolutions", (self.algo,))
if img.type.ndim == 5 and self.num_groups != 1:
raise ValueError("Grouped convolutions not implemented for 3D convolutions")
if (not isinstance(desc.type, CDataType) or
desc.type.ctype != 'cudnnConvolutionDescriptor_t'):
raise TypeError('desc must be cudnnConvolutionDescriptor_t')
alpha = ensure_dt(alpha, _one, 'alpha', img.dtype)
beta = ensure_dt(beta, _zero, 'beta', img.dtype)
return Apply(self, [img, kern, output, desc, alpha, beta],
[output.type()])
def grad(self, inp, grads):
img, kerns, output, desc, alpha, beta = inp
top, = grads
top = gpu_contiguous(top)
d_img = GpuDnnConvGradI(num_groups=self.num_groups)(kerns, top, empty_like(img), desc)
d_kerns = GpuDnnConvGradW(num_groups=self.num_groups)(img, top, empty_like(kerns), desc)
d_alpha = grad_not_implemented(self, 4, alpha)
d_beta = grad_not_implemented(self, 5, beta)
return [d_img * alpha, d_kerns * alpha, top * beta,
DisconnectedType()(), d_alpha, d_beta]
def connection_pattern(self, node):
# not connected to desc
return [[1], [1], [1], [0], [1], [1]]
@staticmethod
def get_out_shape(ishape, kshape, border_mode, subsample, dilation):
"""
This function computes the output shape for a convolution with
the specified parameters. `ishape` and `kshape` can be symbolic
or scalar.
"""
# if ishape and/or kshape are not tuples or list, but rather symbolic
# vectors, turn them into lists of symbolic scalars.
if not isinstance(ishape, (list, tuple)):
ishape = [ishape[i] for i in range(len(subsample) + 2)]
if not isinstance(kshape, (list, tuple)):
kshape = [kshape[i] for i in range(len(subsample) + 2)]
return get_conv_output_shape(
ishape,
kshape,
border_mode,
subsample,
dilation)
def infer_shape(self, node, shape):
return [shape[2]]
class GpuDnnConvGradW(DnnBase):
"""
The convolution gradient with respect to the weights.
Parameters
----------
image
kernel
descr :
The convolution descriptor.
algo : {'none', 'deterministic', 'fft', 'small', 'guess_once',
'guess_on_shape_change', 'time_once', 'time_on_shape_change'}
Default is the value of :attr:`config.dnn.conv.algo_bwd_filter`.
num_groups :
Divides the image, kernel and output tensors into num_groups
separate groups. Each which carry out convolutions separately
"""
_f16_ok = True
__props__ = ('algo', 'inplace', 'num_groups')
check_input = False
params_type = ParamsType(conv_algo=cudnn.cudnnConvolutionBwdFilterAlgo_t,
choose_algo=bool_t, choose_once=bool_t, choose_time=bool_t,
inplace=bool_t,
handle=handle_type,
num_groups=int_t)
def __init__(self, inplace=False, algo=None, num_groups=1):
DnnBase.__init__(self, ["c_code/dnn_conv_base.c", "c_code/dnn_gw.c"],
"APPLY_SPECIFIC(conv_gw)")
self.inplace = bool(inplace)
if self.inplace:
self.destroy_map = {0: [2]}
if algo is None:
algo = config.dnn.conv.algo_bwd_filter
self.algo = algo
assert cudnn.cudnnConvolutionBwdFilterAlgo_t.has_alias(self.algo) or self.algo in SUPPORTED_DNN_CONV_ALGO_RUNTIME
self.conv_algo = cudnn.cudnnConvolutionBwdFilterAlgo_t.CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0
if self.algo not in SUPPORTED_DNN_CONV_ALGO_RUNTIME:
self.conv_algo = self.algo
self.choose_algo = self.algo in SUPPORTED_DNN_CONV_ALGO_RUNTIME
self.choose_once = self.algo in DNN_CONV_ALGO_CHOOSE_ONCE
self.choose_time = self.algo in DNN_CONV_ALGO_CHOOSE_TIME
self.num_groups = num_groups
def __setstate__(self, d):
self.__dict__.update(d)
if not hasattr(self, 'inplace'):
self.inplace = False
if not hasattr(self, 'algo'):
self.algo = config.dnn.conv.algo_bwd_filter
if not hasattr(self, 'num_groups'):
self.num_groups = 1
def grad(self, inp, grads):
img, top, output, desc, alpha, beta = inp
kerns, = grads
kerns = gpu_contiguous(kerns)
d_img = GpuDnnConvGradI(num_groups=self.num_groups)(kerns, top, empty_like(img), desc)
d_top = GpuDnnConv(num_groups=self.num_groups)(img, kerns, empty_like(top), desc)
d_alpha = grad_not_implemented(self, 4, alpha)
d_beta = grad_not_implemented(self, 5, beta)
return (d_img * alpha, d_top * alpha, kerns * beta,
DisconnectedType()(), d_alpha, d_beta)
def connection_pattern(self, node):
# not connected to desc
return [[1], [1], [1], [0], [1], [1]]
def op_may_fail_with_subsample(self, img, desc):
return (version() < 6000 and
img.type.dtype == 'float32' and
img.type.ndim == 5 and
self.algo != 'none' and
desc.owner.op.subsample != (1, 1, 1))
def op_may_fail_with_beta(self, img, beta):
return (version() < 6000 and
img.type.dtype == 'float32' and
self.algo not in ('none', 'deterministic', 'fft', 'small') and
beta is not None and
theano.tensor.extract_constant(beta) != 1)
def make_node(self, img, topgrad, output, desc, alpha=None, beta=None):
if self.op_may_fail_with_subsample(img, desc):
warnings.warn('cuDNN backward filter operation for 3D convolutions may produce bad results '
'with certain cuDNN algorithms depending on the compute capability of your GPU '
'if subsample is not (1, 1, 1). If you encounter problems, consider '
'setting the theano flag "dnn.conv.algo_bwd_filter" to "none".')
if self.op_may_fail_with_beta(img, beta):
warnings.warn('cuDNN backward filter operation for convolutions may produce bad results '
'with certain cuDNN algorithms depending on the compute capability of your GPU '
'if beta != 1. If you encounter problems, consider '
'setting the theano flag "dnn.conv.algo_bwd_filter" to '
'"none", "deterministic", "fft", or "small".')
ctx_name = infer_context_name(img, topgrad, output)
img = as_gpuarray_variable(img, ctx_name)
topgrad = as_gpuarray_variable(topgrad, ctx_name)
output = as_gpuarray_variable(output, ctx_name)
if img.type.ndim not in (4, 5):
raise TypeError('img must be 4D or 5D tensor')
if topgrad.type.ndim not in (4, 5):
raise TypeError('topgrad must be 4D or 5D tensor')
if output.type.ndim not in (4, 5):
raise TypeError('output must be 4D or 5D tensor')
if (img.type.ndim != topgrad.type.ndim or
img.type.ndim != output.type.ndim):
raise TypeError("The number of dimensions of "
"img, topgrad and output must match")
if img.type.ndim == 5 and self.algo not in (cudnn.conv3d_bwd_filter_algorithms +
SUPPORTED_DNN_CONV_ALGO_RUNTIME):
raise ValueError("convolution algo %s can't be used for "
"3d convolutions", (self.algo,))
if (not isinstance(desc.type, CDataType) or
desc.type.ctype != 'cudnnConvolutionDescriptor_t'):
raise TypeError('desc must be cudnnConvolutionDescriptor_t')
alpha = ensure_dt(alpha, _one, 'alpha', img.dtype)
beta = ensure_dt(beta, _zero, 'beta', img.dtype)
return Apply(self, [img, topgrad, output, desc, alpha, beta],
[output.type()])
def infer_shape(self, node, shape):
return [shape[2]]
class GpuDnnConvGradI(DnnBase):
"""
The convolution gradient with respect to the inputs.
Parameters
----------
image
kernel
descr
The convolution descriptor.
algo : {'none', 'deterministic', 'fft', 'fft_tiling', 'winograd', 'guess_once',
'guess_on_shape_change', 'time_once', 'time_on_shape_change'}
Default is the value of :attr:`config.dnn.conv.algo_bwd_data`.
num_groups :
Divides the image, kernel and output tensors into num_groups
separate groups. Each which carry out convolutions separately
"""
_f16_ok = True
__props__ = ('algo', 'inplace', 'num_groups')
check_input = False
params_type = ParamsType(conv_algo=cudnn.cudnnConvolutionBwdDataAlgo_t,
choose_algo=bool_t, choose_once=bool_t, choose_time=bool_t,
inplace=bool_t,
handle=handle_type,
num_groups=int_t)
def __init__(self, inplace=False, algo=None, num_groups=1):
DnnBase.__init__(self, ["c_code/dnn_conv_base.c", "c_code/dnn_gi.c"],
"APPLY_SPECIFIC(conv_gi)")
self.inplace = bool(inplace)
if self.inplace:
self.destroy_map = {0: [2]}
if algo is None:
algo = config.dnn.conv.algo_bwd_data
self.algo = algo
assert cudnn.cudnnConvolutionBwdDataAlgo_t.has_alias(self.algo) or self.algo in SUPPORTED_DNN_CONV_ALGO_RUNTIME
self.conv_algo = cudnn.cudnnConvolutionBwdDataAlgo_t.CUDNN_CONVOLUTION_BWD_DATA_ALGO_0
if self.algo not in SUPPORTED_DNN_CONV_ALGO_RUNTIME:
self.conv_algo = self.algo
self.choose_algo = self.algo in SUPPORTED_DNN_CONV_ALGO_RUNTIME
self.choose_once = self.algo in DNN_CONV_ALGO_CHOOSE_ONCE
self.choose_time = self.algo in DNN_CONV_ALGO_CHOOSE_TIME
self.num_groups = num_groups
def __setstate__(self, d):
self.__dict__.update(d)
if not hasattr(self, 'algo'):
self.algo = config.dnn.conv.algo_bwd_data
if not hasattr(self, 'inplace'):
self.inplace = False
if not hasattr(self, 'num_groups'):
self.num_groups = 1
def grad(self, inp, grads):
kerns, top, output, desc, alpha, beta = inp
img, = grads
img = gpu_contiguous(img)
d_kerns = GpuDnnConvGradW(num_groups=self.num_groups)(img, top, empty_like(kerns), desc)
d_top = GpuDnnConv(num_groups=self.num_groups)(img, kerns, empty_like(top), desc)
d_alpha = grad_not_implemented(self, 4, alpha)
d_beta = grad_not_implemented(self, 5, beta)
return (d_kerns * alpha, d_top * alpha, img * beta,
DisconnectedType()(), d_alpha, d_beta)
def connection_pattern(self, node):
# not connected to desc
return [[1], [1], [1], [0], [1], [1]]
def make_node(self, kern, topgrad, output, desc, alpha=None, beta=None):
ctx_name = infer_context_name(kern, topgrad, output)
kern = as_gpuarray_variable(kern, ctx_name)
topgrad = as_gpuarray_variable(topgrad, ctx_name)
output = as_gpuarray_variable(output, ctx_name)
if kern.type.ndim not in (4, 5):
raise TypeError('kern must be 4D or 5D tensor')
if topgrad.type.ndim not in (4, 5):
raise TypeError('topgrad must be 4D or 5D tensor')
if output.type.ndim not in (4, 5):
raise TypeError('output must be 4D or 5D tensor')
if (kern.type.ndim != topgrad.type.ndim or
kern.type.ndim != output.type.ndim):
raise TypeError("The number of dimensions of "
"kern, topgrad and output must match")
if kern.type.ndim == 5 and self.algo not in (cudnn.conv3d_bwd_data_algorithms +
SUPPORTED_DNN_CONV_ALGO_RUNTIME):
raise ValueError("convolution algo %s can't be used for "
"3d convolutions", (self.algo,))
if (not isinstance(desc.type, CDataType) or
desc.type.ctype != 'cudnnConvolutionDescriptor_t'):
raise TypeError('desc must be cudnnConvolutionDescriptor_t')
alpha = ensure_dt(alpha, _one, 'alpha', kern.dtype)
beta = ensure_dt(beta, _zero, 'beta', kern.dtype)
return Apply(self, [kern, topgrad, output, desc, alpha, beta],
[output.type()])
def infer_shape(self, node, shape):
return [shape[2]]
def dnn_conv(img, kerns, border_mode='valid', subsample=(1, 1), dilation=(1, 1),
conv_mode='conv', direction_hint=None, workmem=None,
algo=None, precision=None, num_groups=1):
"""
GPU convolution using cuDNN from NVIDIA.
The memory layout to use is 'bc01', that is 'batch', 'channel',
'first dim', 'second dim' in that order.
Parameters
----------
img
Images to do the convolution over.
kerns
Convolution filters.
border_mode
One of 'valid', 'full', 'half'; additionally, the padding size
could be directly specified by an integer or a pair of integers.
subsample
Perform subsampling of the output (default: (1, 1)).
dilation
Filter dilation factor. A dilation factor of d is equivalent to a
convolution with d - 1 zeros inserted between neighboring filter
values.
conv_mode
Perform convolution (kernels flipped) or cross-correlation.
One of 'conv', 'cross' (default: 'conv').
direction_hint
Used by graph optimizers to change algorithm choice.
By default, GpuDnnConv will be used to carry out the convolution.
If border_mode is 'valid', subsample is (1, 1), dilation is (1, 1), and
direction_hint is 'bprop weights', it will use GpuDnnConvGradW.
If border_mode is 'full', subsample is (1, 1), dilation is (1, 1), and
direction_hint is *not* 'forward!', it will use GpuDnnConvGradI.
This parameter is used internally by graph optimizers and may be
removed at any time without a deprecation period. You have been warned.
algo : {'none', 'small', 'large', 'fft', 'guess_once', 'guess_on_shape_change', 'time_once', 'time_on_shape_change'}
Convolution implementation to use. Some of its values may
require certain versions of cuDNN to be installed. Default is
the value of :attr:`config.dnn.conv.algo_fwd`.
precision : {'as_input_f32', 'as_input', 'float16', 'float32', 'float64'}
Description of the dtype in which the computation of the convolution
should be done. Possible values are 'as_input', 'float16', 'float32'
and 'float64'. Default is the value of
:attr:`config.dnn.conv.precision`.
num_groups :
Divides the image, kernel and output tensors into num_groups
separate groups. Each which carry out convolutions separately
.. warning:: The cuDNN library only works with GPUs that have a compute
capability of 3.0 or higer. This means that older GPUs will not
work with this Op.
"""
# Establish dtype in which to perform the computation of the convolution
precision = get_precision(precision, [img, kerns])
if workmem is not None:
if algo is not None:
raise ValueError("You can't use both algo and workmem")
warnings.warn("workmem is deprecated, use algo instead", stacklevel=2)
algo = workmem
fgraph = getattr(img, 'fgraph', None) or getattr(kerns, 'fgraph', None)
ctx_name = infer_context_name(img, kerns)
if (border_mode == 'valid' and subsample == (1, 1) and dilation == (1, 1) and
direction_hint == 'bprop weights' and num_groups == 1):
# Special case: We are asked to use GpuDnnConvGradW. We need to set
# up a suitable 'fake' convolution to compute the gradient for.
img = gpu_contiguous(img.dimshuffle(1, 0, 2, 3))