-
Notifications
You must be signed in to change notification settings - Fork 0
/
chainerc2d.py
1109 lines (920 loc) · 43.4 KB
/
chainerc2d.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
'''
Created on Dec 2, 2017
@author: ARL
'''
###function
import numpy as np
#https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.apply_over_axes.html#numpy.apply_over_axes
import chainer
from chainer import configuration
from chainer import cuda
from chainer import function_node
import chainer.functions as cf
from chainer.utils import argument
import chainercutils as conv
from chainer.utils import type_check
#from chainer.functions.connection import convolution_2d
from chainer import initializers
from chainer import link
from chainer import variable
#from chainer.functions.connection import convolution_2d
if cuda.cudnn_enabled:
cudnn = cuda.cudnn
libcudnn = cuda.cuda.cudnn
_cudnn_version = libcudnn.getVersion()
_fwd_pref = libcudnn.CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT
_bwd_filter_pref = \
libcudnn.CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT
_algorithm_fwd = {}
_algorithm_bwd_filter = {}
def _pair(x):
if hasattr(x, '__getitem__'):
return x
return x, x
def _get_algorithm_fwd(
x, W, y, conv_param, handle, x_desc, filter_desc, conv_desc, y_desc,
workspace):
key = (x.shape, W.shape, y.shape, conv_param)
if key in _algorithm_fwd:
return _algorithm_fwd[key]
ret = libcudnn.findConvolutionForwardAlgorithmEx(
handle, x_desc.value, x.data.ptr, filter_desc.value, W.data.ptr,
conv_desc.value, y_desc.value, y.data.ptr, 1, workspace.data.ptr,
workspace.size)
algo = ret[0]['algo']
_algorithm_fwd[key] = algo
return algo
def _get_algorithm_bwd_filter(
x, dy, dW, conv_param, handle, x_desc, dy_desc, conv_desc, filter_desc,
workspace):
key = (x.shape, dW.shape, dy.shape, conv_param)
if key in _algorithm_bwd_filter:
return _algorithm_bwd_filter[key]
ret = libcudnn.findConvolutionBackwardFilterAlgorithmEx(
handle, x_desc.value, x.data.ptr, dy_desc.value, dy.data.ptr,
conv_desc.value, filter_desc.value, dW.data.ptr, 1,
workspace.data.ptr, workspace.size)
algo = ret[0]['algo']
_algorithm_bwd_filter[key] = algo
return algo
class Convar2DFunc(function_node.FunctionNode):
def __init__(self, stride=1, pad=0, cover_all=False, sqrt=False,noB=1,KCD=False,
verbose=False,nobias=False, **kwargs):
argument.check_unexpected_kwargs(
kwargs,
deterministic="deterministic argument is not supported anymore. "
"Use chainer.using_config('cudnn_deterministic', value) context "
"where value is either `True` or `False`.",
requires_x_grad="requires_x_grad argument is not supported "
"anymore. Just remove the argument. Note that whether to compute "
"the gradient w.r.t. x is automatically decided during "
"backpropagation."
)
dilate, = argument.parse_kwargs(kwargs, ('dilate', 1))
self.sqrt=sqrt
self.noB=noB
self.KCD=KCD
self.V=verbose
self.sy, self.sx = _pair(stride)
self.ph, self.pw = _pair(pad)
self.cover_all = cover_all
self.dy, self.dx = _pair(dilate)
def check_type_forward(self, in_types):
n_in = in_types.size()
type_check.expect(2 <= n_in, n_in <= 3)
x_type = in_types[0]
w_type = in_types[1]
type_check.expect(
x_type.dtype.kind == 'f',
w_type.dtype.kind == 'f',
x_type.ndim == 4,
w_type.ndim == 4,
x_type.shape[1] == w_type.shape[1],
)
if type_check.eval(n_in) == 3:
b_type = in_types[2]
type_check.expect(
b_type.dtype == x_type.dtype,
b_type.ndim == 1,
b_type.shape[0] == w_type.shape[0],
)
def VecVari(self,array,W,B=None,sqrt=False,KCD=False,t=0,**kwargs):
"""No print version, for speedtests
params:
array(array): input data
W(array): weights
B(array): bias
sqrt[-1,0,1]: -1:abs, 0:squared, 1:squared+sqrt
KCD(bool): keep channel data, i.e.: does not sum the channel axis, output is more massive though
t[0,1,2]: the 3 version to test for mathematical equivalency
**kwargs: just a way to prevent error with function changes
"""
arrs=array.shape
ashp=W.shape
dstp=arrs[0]-1 if not((arrs[0]-1)==0) else 1
#array=np.expand_dims(array,len(array.shape)//2)
#print("VECVARI:: B? {},SQRT {}, KCD {}, T {}".format(not(B is None),bool(sqrt),bool(KCD),t))
xi=(-2,-1)
x2=(-3,-2,-1)
size=np.sum(W,axis=xi,keepdims=True)#shape=(outputs, channel)
mul=array*W
mean=np.sum(mul,xi,keepdims=1)/np.broadcast_to([ashp[-2]*ashp[-1]],(3,1,1))
i=np.square(mul-mean)/size
if KCD:
out=np.sum(i,axis=xi)
else:
out=np.rollaxis(np.sum(i,axis=x2),-1,1)
if sqrt:
out=np.sqrt(out)
if not(B is None):
try:
out=out+B
except:
B=np.reshape(B,(*B.shape,*[1 for _ in range(len(ashp)-len(B.shape)-1)]))
out=out+B
if KCD:
return(np.transpose(np.reshape(out,(arrs[0],arrs[1],arrs[2],ashp[0]*arrs[-3])),(0,3,1,2)))
else:
assert out.shape==(arrs[0],ashp[0],arrs[1],arrs[2])
return(out)
def forward_cpu(self, inputs):
self.retain_inputs((0, 1)) # retain only x and W
x, W = inputs[:2]
b = inputs[2] if len(inputs) == 3 else None
if not all([isinstance(i, np.ndarray) for i in inputs]):
if b is not None:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}, type(b): {2}'
.format(type(W), type(x), type(b)))
else:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}'
.format(type(W), type(x)))
kh, kw = W.shape[2:]
col = conv.im2col_cpuV2(
x, kh, kw, self.sy, self.sx, self.ph, self.pw,
cover_all=self.cover_all, dy=self.dy, dx=self.dx)
return(self.VecVari(col, W, B=b,))
def forward_gpu(self, inputs):
self.retain_inputs((0, 1)) # retain only x and W
x, W = inputs[:2]
b = inputs[2] if len(inputs) == 3 else None
if not all([isinstance(i, cuda.ndarray) for i in inputs]):
if b is not None:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}, type(b): {2}'
.format(type(W), type(x), type(b)))
else:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}'
.format(type(W), type(x)))
out_c, _, kh, kw = W.shape
n, c, h, w = x.shape
out_h = conv.get_conv_outsize(h, kh, self.sy, self.ph,
cover_all=self.cover_all, d=self.dy)
assert out_h > 0, 'Height in the output should be positive.'
out_w = conv.get_conv_outsize(w, kw, self.sx, self.pw,
cover_all=self.cover_all, d=self.dx)
assert out_w > 0, 'Width in the output should be positive.'
y = cuda.cupy.empty((n, out_c, out_h, out_w), dtype=x.dtype)
if (not self.cover_all and chainer.should_use_cudnn('>=auto') and
x.dtype == W.dtype and
((self.dy == 1 and self.dx == 1) or _cudnn_version >= 6000)):
x = cuda.cupy.ascontiguousarray(x)
W = cuda.cupy.ascontiguousarray(W)
if b is not None:
b = cuda.cupy.ascontiguousarray(b)
use_tensor_core = chainer.should_use_cudnn_tensor_core(x.dtype)
handle = cudnn.get_handle()
x_desc = cudnn.create_tensor_descriptor(x)
y_desc = cudnn.create_tensor_descriptor(y)
filter_desc = cudnn.create_filter_descriptor(W)
conv_param = ((self.ph, self.pw), (self.sy, self.sx), x.dtype)
dilation = (self.dy, self.dx)
conv_desc = cudnn.create_convolution_descriptor(
*conv_param, dilation=dilation,
use_tensor_core=use_tensor_core)
if b is not None:
bias_desc = cudnn.create_tensor_descriptor(
b[None, :, None, None])
workspace_size = cuda.get_max_workspace_size()
workspace = cuda.cupy.empty((workspace_size,), dtype='b')
if configuration.config.autotune and _cudnn_version >= 5000:
algo = _get_algorithm_fwd(
x, W, y, conv_param + (dilation,), handle, x_desc,
filter_desc, conv_desc, y_desc, workspace)
else:
algo = libcudnn.getConvolutionForwardAlgorithm(
handle, x_desc.value, filter_desc.value,
conv_desc.value, y_desc.value, _fwd_pref, workspace_size)
if use_tensor_core:
# Only CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM
# supports Tensor-Core in cuDNN7.
algo = libcudnn.CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM # NOQA
oz_dtype = 'd' if x.dtype == 'd' else 'f'
one = np.array(1, dtype=oz_dtype).ctypes
zero = np.array(0, dtype=oz_dtype).ctypes
libcudnn.convolutionForward(
handle, one.data, x_desc.value, x.data.ptr,
filter_desc.value, W.data.ptr, conv_desc.value,
algo, workspace.data.ptr, workspace_size, zero.data,
y_desc.value, y.data.ptr)
# TODO(beam2d): Support unshared bias
if b is not None:
cudnn.add_tensor(
handle, one.data, bias_desc.value, b.data.ptr,
one.data, y_desc.value, y.data.ptr)
else:
# Implementation using im2col
col = conv.im2col_gpu(
x, kh, kw, self.sy, self.sx, self.ph, self.pw,
cover_all=self.cover_all, dy=self.dy, dx=self.dx)
y = cuda.cupy.tensordot(col, W, ((1, 2, 3), (1, 2, 3))).astype(x.dtype, copy=False)
# TODO(beam2d): Support unshared bias
if b is not None:
y += b
y = cuda.cupy.rollaxis(y, 3, 1)
return y,
def backward(self, indexes, grad_outputs):
x, W = self.get_retained_inputs()
gy, = grad_outputs
ret = []
if 0 in indexes:
xh, xw = x.shape[2:]
gx = chainer.functions.deconvolution_2d(
gy, W, stride=(self.sy, self.sx), pad=(self.ph, self.pw),
outsize=(xh, xw), dilate=(self.dy, self.dx))
ret.append(gx)
if 1 in indexes:
gW, = Convolution2DGradW(self).apply((x, gy))
ret.append(gW)
if 2 in indexes:
gb = chainer.functions.sum(gy, axis=(0, 2, 3))
ret.append(gb)
return ret
class Convolution2DGradW(function_node.FunctionNode):
def __init__(self, conv2d):
W_node = conv2d.inputs[1]
self.kh, self.kw = W_node.shape[2:]
self.sy = conv2d.sy
self.sx = conv2d.sx
self.ph = conv2d.ph
self.pw = conv2d.pw
self.dy = conv2d.dy
self.dx = conv2d.dx
self.cover_all = conv2d.cover_all
self.W_dtype = W_node.dtype
def forward_cpu(self, inputs):
self.retain_inputs((0, 1))
x, gy = inputs
col = conv.im2col_cpuV2(
x, self.kh, self.kw, self.sy, self.sx, self.ph, self.pw,
cover_all=self.cover_all, dy=self.dy, dx=self.dx,og=True)
# NumPy raises an error when the array is not contiguous.
# See: https://github.com/chainer/chainer/issues/2744
# TODO(niboshi): Remove this code when NumPy is fixed.
if (not (gy.flags.c_contiguous or gy.flags.f_contiguous) and
1 in gy.shape):
gy = np.ascontiguousarray(gy)
gW = np.tensordot(
gy, col, ((0, 2, 3), (0, 4, 5))).astype(self.W_dtype, copy=False)
return gW,
def forward_gpu(self, inputs):
self.retain_inputs((0, 1))
x, gy = inputs
_, out_c, out_h, out_w = gy.shape
n, c, h, w = x.shape
if (self.cover_all or not chainer.should_use_cudnn('>=auto') or
x.dtype != self.W_dtype or
((self.dy > 1 or self.dx > 1) and _cudnn_version < 6000)):
col = conv.im2col_gpu(
x, self.kh, self.kw, self.sy, self.sx, self.ph, self.pw,
cover_all=self.cover_all, dy=self.dy, dx=self.dx)
gW = cuda.cupy.tensordot( gy, col, ((0, 2, 3), (0, 4, 5))).astype(self.W_dtype,
copy=False)
return gW,
gW = cuda.cupy.empty((out_c, c, self.kh, self.kw), dtype=self.W_dtype)
x = cuda.cupy.ascontiguousarray(x)
gy = cuda.cupy.ascontiguousarray(gy)
use_tensor_core = chainer.should_use_cudnn_tensor_core(x.dtype)
handle = cudnn.get_handle()
x_desc = cudnn.create_tensor_descriptor(x)
gy_desc = cudnn.create_tensor_descriptor(gy)
filter_desc = cudnn.create_filter_descriptor(gW)
conv_param = (self.ph, self.pw), (self.sy, self.sx), x.dtype
dilation = (self.dy, self.dx)
conv_desc = cudnn.create_convolution_descriptor(
*conv_param, dilation=dilation,
use_tensor_core=use_tensor_core)
oz_dtype = 'd' if x.dtype == 'd' else 'f'
one = np.array(1, dtype=oz_dtype).ctypes
zero = np.array(0, dtype=oz_dtype).ctypes
workspace_size = cuda.get_max_workspace_size()
workspace = cuda.cupy.empty((workspace_size,), dtype='b')
if configuration.config.cudnn_deterministic:
algo = libcudnn.CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1
elif configuration.config.autotune and _cudnn_version >= 5000:
algo = _get_algorithm_bwd_filter(
x, gy, gW, conv_param + (dilation,), handle, x_desc, gy_desc,
conv_desc, filter_desc, workspace)
else:
algo = libcudnn.getConvolutionBackwardFilterAlgorithm(
handle, x_desc.value, gy_desc.value, conv_desc.value,
filter_desc.value, _bwd_filter_pref, workspace_size)
if use_tensor_core:
# Only CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1 supports
# Tensor-Core in cuDNN7.
algo = libcudnn.CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1
libcudnn.convolutionBackwardFilter_v3(
handle, one.data, x_desc.value, x.data.ptr, gy_desc.value,
gy.data.ptr, conv_desc.value, algo, workspace.data.ptr,
workspace_size, zero.data, filter_desc.value, gW.data.ptr)
return gW,
def backward(self, indexes, grad_outputs):
x, gy = self.get_retained_inputs()
ggW, = grad_outputs
ret = []
if 0 in indexes:
xh, xw = x.shape[2:]
gx = chainer.functions.deconvolution_2d(
gy, ggW, stride=(self.sy, self.sx), pad=(self.ph, self.pw),
outsize=(xh, xw), dilate=(self.dy, self.dx))
ret.append(gx)
if 1 in indexes:
ggy = convar_2d(
x, ggW, stride=(self.sy, self.sx), pad=(self.ph, self.pw),
cover_all=self.cover_all, dilate=(self.dy, self.dx))
ret.append(ggy)
return ret
def convar_2d(x, W, b=None, stride=1, pad=0, cover_all=False, **kwargs):
"""convolution_2d(x, W, b=None, stride=1, pad=0, cover_all=False)
Two-dimensional convolution function.
This is an implementation of two-dimensional convolution in ConvNets.
It takes three variables: the input image ``x``, the filter weight ``W``,
and the bias vector ``b``.
Notation: here is a notation for dimensionalities.
- :math:`n` is the batch size.
- :math:`c_I` and :math:`c_O` are the number of the input and output
channels, respectively.
- :math:`h_I` and :math:`w_I` are the height and width of the input image,
respectively.
- :math:`h_K` and :math:`w_K` are the height and width of the filters,
respectively.
- :math:`h_P` and :math:`w_P` are the height and width of the spatial
padding size, respectively.
Then the ``Convolution2D`` function computes correlations between filters
and patches of size :math:`(h_K, w_K)` in ``x``.
Note that correlation here is equivalent to the inner product between
expanded vectors.
Patches are extracted at positions shifted by multiples of ``stride`` from
the first position ``(-h_P, -w_P)`` for each spatial axis.
The right-most (or bottom-most) patches do not run over the padded spatial
size.
Let :math:`(s_Y, s_X)` be the stride of filter application. Then, the
output size :math:`(h_O, w_O)` is determined by the following equations:
.. math::
h_O &= (h_I + 2h_P - h_K) / s_Y + 1,\\\\
w_O &= (w_I + 2w_P - w_K) / s_X + 1.
If ``cover_all`` option is ``True``, the filter will cover the all
spatial locations. So, if the last stride of filter does not cover the
end of spatial locations, an addtional stride will be applied to the end
part of spatial locations. In this case, the output size :math:`(h_O, w_O)`
is determined by the following equations:
.. math::
h_O &= (h_I + 2h_P - h_K + s_Y - 1) / s_Y + 1,\\\\
w_O &= (w_I + 2w_P - w_K + s_X - 1) / s_X + 1.
If the bias vector is given, then it is added to all spatial locations of
the output of convolution.
The output of this function can be non-deterministic when it uses cuDNN.
If ``chainer.configuration.config.cudnn_deterministic`` is ``True`` and
cuDNN version is >= v3, it forces cuDNN to use a deterministic algorithm.
Convolution links can use a feature of cuDNN called autotuning, which
selects the most efficient CNN algorithm for images of fixed-size,
can provide a significant performance boost for fixed neural nets.
To enable, set `chainer.using_config('autotune', True)`
When the dilation factor is greater than one, cuDNN is not used unless
the version is 6.0 or higher.
.. warning::
``deterministic`` argument is not supported anymore since v2.
Instead, use ``chainer.using_config('cudnn_deterministic', value)``
(value is either ``True`` or ``False``).
See :func:`chainer.using_config`.
Args:
x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`):
Input variable of shape :math:`(n, c_I, h_I, w_I)`.
W (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`):
Weight variable of shape :math:`(c_O, c_I, h_K, w_K)`.
b (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
:class:`cupy.ndarray`): Bias variable of length :math:`c_O` (optional).
stride (:class:`int` or pair of :class:`int` s):
Stride of filter applications. ``stride=s`` and ``stride=(s, s)``
are equivalent.
pad (:class:`int` or pair of :class:`int` s):
Spatial padding width for input arrays.
``pad=p`` and ``pad=(p, p)`` are equivalent.
cover_all (bool): If ``True``, all spatial locations are convoluted
into some output pixels.
dilate (int or pair of ints): Dilation factor of filter applications.
``dilate=d`` and ``dilate=(d, d)`` are equivalent.
Returns:
~chainer.Variable:
Output variable of shape :math:`(n, c_O, h_O, w_O)`.
.. seealso:: :class:`~chainer.links.Convolution2D`
.. admonition:: Example
>>> n = 10
>>> c_i, c_o = 3, 1
>>> h_i, w_i = 30, 40
>>> h_k, w_k = 10, 10
>>> h_p, w_p = 5, 5
>>> x = np.random.uniform(0, 1, (n, c_i, h_i, w_i)).astype('f')
>>> x.shape
(10, 3, 30, 40)
>>> W = np.random.uniform(0, 1, (c_o, c_i, h_k, w_k)).astype('f')
>>> W.shape
(1, 3, 10, 10)
>>> b = np.random.uniform(0, 1, (c_o,)).astype('f')
>>> b.shape
(1,)
>>> s_y, s_x = 5, 7
>>> y = F.convolution_2d(x, W, b, stride=(s_y, s_x), pad=(h_p, w_p))
>>> y.shape
(10, 1, 7, 6)
>>> h_o = int((h_i + 2 * h_p - h_k) / s_y + 1)
>>> w_o = int((w_i + 2 * w_p - w_k) / s_x + 1)
>>> y.shape == (n, c_o, h_o, w_o)
True
>>> y = F.convolution_2d(x, W, b, stride=(s_y, s_x), pad=(h_p, w_p), \
cover_all=True)
>>> y.shape == (n, c_o, h_o, w_o + 1)
True
"""
argument.check_unexpected_kwargs(
kwargs, deterministic="deterministic argument is not "
"supported anymore. "
"Use chainer.using_config('cudnn_deterministic', value) "
"context where value is either `True` or `False`.")
dilate, = argument.parse_kwargs(kwargs, ('dilate', 1))
fnode = Convar2DFunc(stride, pad, cover_all, dilate=dilate,**kwargs)
if b is None:
args = x, W
else:
args = x, W, b
y, = fnode.apply(args)
return y
###link
class Convar2D(link.Link):#main func
"""__init__(self, in_channels, out_channels, ksize=None, stride=1, pad=0, nobias=False, initialW=None, initial_bias=None)
.. warning::
``deterministic`` argument is not supported anymore since v2.
Instead, use ``chainer.using_config('cudnn_deterministic', value``
(value is either ``True`` or ``False``).
See :func:`chainer.using_config`.
Args:
in_channels (int or None): Number of channels of input arrays.
If ``None``, parameter initialization will be deferred until the
first forward data pass at which time the size will be determined.
out_channels (int): Number of channels of output arrays.
ksize (int or pair of ints): Size of filters (a.k.a. kernels).
``ksize=k`` and ``ksize=(k, k)`` are equivalent.
stride (int or pair of ints): Stride of filter applications.
``stride=s`` and ``stride=(s, s)`` are equivalent.
pad (int or pair of ints): Spatial padding width for input arrays.
``pad=p`` and ``pad=(p, p)`` are equivalent.
nobias (bool): If ``True``, then this link does not use the bias term.
initialW (:ref:`initializer <initializer>`): Initializer to
initialize the weight. When it is :class:`numpy.ndarray`,
its ``ndim`` should be 4.
initial_bias (:ref:`initializer <initializer>`): Initializer to
initialize the bias. If ``None``, the bias will be initialized to
zero. When it is :class:`numpy.ndarray`, its ``ndim`` should be 1.
.. seealso::
See :func:`chainer.functions.convolution_2d` for the definition of
two-dimensional convolution.
Attributes:
W (~chainer.Variable): Weight parameter.
b (~chainer.Variable): Bias parameter.
.. admonition:: Example
There are several ways to make a Convolution2D link.
Let an input vector ``x`` be:
>>> x = np.arange(1 * 3 * 10 * 10, dtype='f').reshape(1, 3, 10, 10)
1. Give the first three arguments explicitly:
>>> l = L.Convolution2D(3, 7, 5)
>>> y = l(x)
>>> y.shape
(1, 7, 6, 6)
2. Omit ``in_channels`` or fill it with ``None``:
The below two cases are the same.
>>> l = L.Convolution2D(7, 5)
>>> y = l(x)
>>> y.shape
(1, 7, 6, 6)
>>> l = L.Convolution2D(None, 7, 5)
>>> y = l(x)
>>> y.shape
(1, 7, 6, 6)
When you omit the first argument, you need to specify the other
subsequent arguments from ``stride`` as keyword auguments. So the
below two cases are the same.
>>> l = L.Convolution2D(7, 5, stride=1, pad=0)
>>> y = l(x)
>>> y.shape
(1, 7, 6, 6)
>>> l = L.Convolution2D(None, 7, 5, 1, 0)
>>> y = l(x)
>>> y.shape
(1, 7, 6, 6)
""" # NOQA
def __init__(self, in_channels:int, out_channels:int, filtr:(tuple,list), sqrt=False,noB=0,
KCD=False,
verbose=False,stride=1, pad=0, initW=initializers.GlorotUniform(scale=1.2,dtype=np.float32),
initB=initializers.GlorotUniform(scale=1.2,dtype=np.float32),bias_dept=2, **kwargs):
"""
input channels,
number of outputs
window
"""
super(Convar2D, self).__init__()
argument.check_unexpected_kwargs(
kwargs, deterministic="deterministic argument is not "
"supported anymore. "
"Use chainer.using_config('cudnn_deterministic', value) "
"context where value is either `True` or `False`.")
dilate, = argument.parse_kwargs(kwargs, ('dilate', 1))
#if filter is None:
# out_channels, ksize, in_channels = in_channels, out_channels, None
self.filter = filtr
self.sqrt=sqrt
self.noB=noB
self.V=verbose
self.KCD=KCD
self.stride = _pair(stride)
self.pad = _pair(pad)
self.dilate = _pair(dilate)
self.out_channels = out_channels
with self.init_scope():
#W_initializer = initializers._get_initializer(initW)
self.W = variable.Parameter(initW)
if in_channels is not None:
self._initialize_params(in_channels)
if noB:
self.b = None
else:
if initB is None:
initB = 0
#bias_initializer = initializers._get_initializer(initB)
self.b = variable.Parameter(initB, (self.out_channel))#out_channels)
def _initialize_params(self, in_channels):
if len(self.filter)==3:
in_channels,kh,kw = self.filter
else:
kh, kw = _pair(self.filter)
self.W_shape = (self.out_channels, in_channels, kh, kw)
self.W.initialize(self.W_shape)
if not(self.noB):
self.B_shape=(self.out_channel,)
self.B.initialize(self.B_shape)
def __call__(self, x):
"""Applies the convolution layer.
Args:
x (~chainer.Variable): Input image.
Returns:
~chainer.Variable: Output of the convolution.
"""
if self.W.data is None:
self._initialize_params(x.shape[1])
return convar_2d(
x, self.W, self.b, self.stride, self.pad, dilate=self.dilate, sqrt=self.sqrt,noB=self.noB,
sizz=self.sizz,KCD=self.KCD,verbose=self.V,stride=self.stride, pad=self.pad,nobias=False,)
####deconv
if cuda.cudnn_enabled:
cudnn = cuda.cudnn
libcudnn = cuda.cuda.cudnn
_cudnn_version_ = libcudnn.getVersion()
_fwd_pref = libcudnn.CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT
_bwd_filter_pref = \
libcudnn.CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT
_bwd_data_pref = \
libcudnn.CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT
_algorithm = {}
def get_algorithm(W, dy, dx, conv_param, handle, filter_desc, dy_desc,
conv_desc, dx_desc, workspace):
key = (dx.shape, W.shape, dy.shape, conv_param)
if key in _algorithm:
return _algorithm[key]
ret = libcudnn.findConvolutionBackwardDataAlgorithmEx(
handle, filter_desc.value, W.data.ptr, dy_desc.value, dy.data.ptr,
conv_desc.value, dx_desc.value, dx.data.ptr, 1, workspace.data.ptr,
workspace.size)
algo = ret[0]['algo']
_algorithm[key] = algo
return algo
class Deconvolution2DFunction(function_node.FunctionNode):
cover_all = None
def __init__(self, stride=1, pad=0, outsize=None, **kwargs):
argument.check_unexpected_kwargs(
kwargs,
deterministic="deterministic argument is not supported anymore. "
"Use chainer.using_config('cudnn_deterministic', value) context "
"where value is either `True` or `False`.",
requires_x_grad="requires_x_grad argument is not supported "
"anymore. Just remove the argument. Note that whether to compute "
"the gradient w.r.t. x is automatically decided during "
"backpropagation."
)
dilate, = argument.parse_kwargs(kwargs, ('dilate', 1))
self.sy, self.sx = _pair(stride)
self.ph, self.pw = _pair(pad)
self.outh, self.outw = (None, None) if outsize is None else outsize
self.dy, self.dx = _pair(dilate)
def check_type_forward(self, in_types):
n_in = in_types.size()
type_check.expect(2 <= n_in, n_in <= 3)
x_type, w_type = in_types[:2]
type_check.expect(
x_type.dtype.kind == 'f',
w_type.dtype.kind == 'f',
x_type.ndim == 4,
w_type.ndim == 4,
x_type.shape[1] == w_type.shape[0]
)
if self.outh is not None:
lower_bound = conv.get_conv_outsize(
self.outh, w_type.shape[2], self.sy, self.ph,
d=self.dy)
upper_bound = conv.get_conv_outsize(
self.outh, w_type.shape[2], self.sy, self.ph, cover_all=True,
d=self.dy)
type_check.expect(
lower_bound <= x_type.shape[2],
x_type.shape[2] <= upper_bound)
if self.outw is not None:
lower_bound = conv.get_conv_outsize(
self.outw, w_type.shape[3], self.sx, self.pw,
d=self.dx)
upper_bound = conv.get_conv_outsize(
self.outw, w_type.shape[3], self.sx, self.pw, cover_all=True,
d=self.dx)
type_check.expect(
lower_bound <= x_type.shape[3],
x_type.shape[3] <= upper_bound)
if type_check.eval(n_in) == 3:
b_type = in_types[2]
type_check.expect(
b_type.dtype == x_type.dtype,
b_type.ndim == 1,
b_type.shape[0] == w_type.shape[1]
)
def forward_cpu(self, inputs):
self.retain_inputs((0, 1)) # only retain x and W
x, W = inputs[:2]
b = inputs[2] if len(inputs) == 3 else None
if not all([isinstance(i, np.ndarray) for i in inputs]):
if b is not None:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}, type(b): {2}'
.format(type(W), type(x), type(b)))
else:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}'
.format(type(W), type(x)))
kh, kw = W.shape[2:]
_, _, h, w = x.shape
gcol = np.tensordot(W, x, (0, 1)).astype(x.dtype, copy=False)
# - k, m, n: shape of out_channel
# - b: number of inputs
# - h, w: height and width of kernels
# k, m, n, b, h, w -> b, k, m, n, h, w
gcol = np.rollaxis(gcol, 3)
if self.outh is None:
self.outh = conv.get_deconv_outsize(h, kh, self.sy, self.ph,
d=self.dy)
assert self.outh > 0, 'Height in the output should be positive.'
if self.outw is None:
self.outw = conv.get_deconv_outsize(w, kw, self.sx, self.pw,
d=self.dx)
assert self.outw > 0, 'Width in the output should be positive.'
y = conv.col2im_cpuV2(
gcol, self.sy, self.sx, self.ph, self.pw, self.outh, self.outw,
dy=self.dy, dx=self.dx,og=True)
# b, k, h, w
if b is not None:
y += b.reshape(1, b.size, 1, 1)
return y,
def forward_gpu(self, inputs):
self.retain_inputs((0, 1)) # only retain x and W
x, W = inputs[:2]
b = inputs[2] if len(inputs) == 3 else None
if not all([isinstance(i, cuda.ndarray) for i in inputs]):
if b is not None:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}, type(b): {2}'
.format(type(W), type(x), type(b)))
else:
raise ValueError('numpy and cupy must not be used together\n'
'type(W): {0}, type(x): {1}'
.format(type(W), type(x)))
kh, kw = W.shape[2:]
n, in_c, in_h, in_w = x.shape
c = W.shape[1] # out_c
if self.outh is None:
self.outh = conv.get_deconv_outsize(in_h, kh, self.sy, self.ph,
d=self.dy)
assert self.outh > 0, 'Height in the output should be positive.'
if self.outw is None:
self.outw = conv.get_deconv_outsize(in_w, kw, self.sx, self.pw,
d=self.dx)
assert self.outw > 0, 'Width in the output should be positive.'
self._set_cover_all(x, W)
if (not self.cover_all and chainer.should_use_cudnn('>=auto') and
x.dtype == W.dtype and
((self.dy == 1 and self.dx == 1) or _cudnn_version_ >= 6000)):
x = cuda.cupy.ascontiguousarray(x)
W = cuda.cupy.ascontiguousarray(W)
if b is not None:
b = cuda.cupy.ascontiguousarray(b)
use_tensor_core = chainer.should_use_cudnn_tensor_core(x.dtype)
handle = cudnn.get_handle()
x_desc = cudnn.create_tensor_descriptor(x)
y = cuda.cupy.empty((n, c, self.outh, self.outw),
dtype=x.dtype)
y_desc = cudnn.create_tensor_descriptor(y)
filter_desc = cudnn.create_filter_descriptor(W)
conv_param = (self.ph, self.pw), (self.sy, self.sx), x.dtype
dilation = (self.dy, self.dx)
conv_desc = cudnn.create_convolution_descriptor(
*conv_param, dilation=dilation,
use_tensor_core=use_tensor_core)
if b is not None:
bias_desc = cudnn.create_tensor_descriptor(
b[None, :, None, None])
oz_dtype = 'd' if x.dtype == 'd' else 'f'
one = np.array(1, dtype=oz_dtype).ctypes
zero = np.array(0, dtype=oz_dtype).ctypes
workspace_size = cuda.get_max_workspace_size()
workspace = cuda.cupy.empty((workspace_size,), dtype='b')
if configuration.config.cudnn_deterministic:
algo = libcudnn.CUDNN_CONVOLUTION_BWD_DATA_ALGO_1
elif configuration.config.autotune and _cudnn_version_ >= 5000:
algo = get_algorithm(
W, x, y, conv_param + (dilation,), handle, filter_desc,
x_desc, conv_desc, y_desc, workspace)
else:
algo = libcudnn.getConvolutionBackwardDataAlgorithm(
handle, filter_desc.value, x_desc.value, conv_desc.value,
y_desc.value, _bwd_data_pref, workspace_size)
if use_tensor_core:
# Only CUDNN_CONVOLUTION_BWD_DATA_ALGO_1 supports
# Tensor-Core in cuDNN7
algo = libcudnn.CUDNN_CONVOLUTION_BWD_DATA_ALGO_1
libcudnn.convolutionBackwardData_v3(
handle, one.data, filter_desc.value, W.data.ptr,
x_desc.value, x.data.ptr, conv_desc.value,
algo, workspace.data.ptr, workspace_size,
zero.data, y_desc.value, y.data.ptr)
if b is not None:
cudnn.add_tensor(
handle, one.data, bias_desc.value, b.data.ptr,
one.data, y_desc.value, y.data.ptr)
else:
gcol = cuda.cupy.tensordot(W, x, (0, 1)).astype(x.dtype,
copy=False)
# - k, m, n: shape of out_channel
# - b: number of inputs
# - h, w: height and width of kernels
# k, m, n, b, h, w -> b, k, m, n, h, w
gcol = cuda.cupy.rollaxis(gcol, 3)
y = conv.col2im_gpu(
gcol, self.sy, self.sx, self.ph, self.pw, self.outh, self.outw,
dy=self.dy, dx=self.dx)
if b is not None:
y += b.reshape(1, b.size, 1, 1)
return y,
def backward(self, indexes, grad_outputs):
x, W = self.get_retained_inputs()
gy, = grad_outputs
ret = []
if 0 in indexes:
if self.cover_all is None:
self._set_cover_all(x, W)
gx = chainer.functions.convolution_2d(
gy, W, stride=(self.sy, self.sx), pad=(self.ph, self.pw),
cover_all=self.cover_all, dilate=(self.dy, self.dx))
ret.append(gx)
if 1 in indexes:
if self.cover_all is None:
self._set_cover_all(x, W)
gW, = Convolution2DGradW(self).apply((gy, x))
ret.append(gW)
if 2 in indexes:
gb = chainer.functions.sum(gy, axis=(0, 2, 3))
ret.append(gb)
return ret
def _set_cover_all(self, x, W):
in_h, in_w = x.shape[2:]
kh, kw = W.shape[2:]
self.cover_all = (
in_h != conv.get_conv_outsize(self.outh, kh, self.sy,
self.ph, d=self.dy) or
in_w != conv.get_conv_outsize(self.outw, kw, self.sx,
self.pw, d=self.dx))
def deconvolution_2d(x, W, b=None, stride=1, pad=0, outsize=None, **kwargs):
"""deconvolution_2d(x, W, b=None, stride=1, pad=0, outsize=None)
Two dimensional deconvolution function.
This is an implementation of two-dimensional deconvolution. In most of deep
learning frameworks and papers, this function is called
**transposed convolution**. But because of historical reasons (e.g. paper
by Ziller `Deconvolutional Networks`_) and backward compatibility, this
function is called **deconvolution** in Chainer.