test_conv2d_op.py 10.5 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
import unittest
import numpy as np
D
dzhwinter 已提交
17

18
import paddle.fluid.core as core
H
hedaoyuan 已提交
19
from op_test import OpTest
20 21


C
chengduoZH 已提交
22 23 24 25 26 27 28
def conv2d_forward_naive(input, filter, group, conv_param):
    in_n, in_c, in_h, in_w = input.shape
    out_c, f_c, f_h, f_w = filter.shape
    assert f_c * group == in_c
    assert np.mod(out_c, group) == 0
    sub_out_c = out_c / group

C
chengduoZH 已提交
29 30 31 32
    stride, pad, dilation = conv_param['stride'], conv_param['pad'], conv_param[
        'dilation']
    out_h = 1 + (in_h + 2 * pad[0] - (dilation[0] * (f_h - 1) + 1)) / stride[0]
    out_w = 1 + (in_w + 2 * pad[1] - (dilation[1] * (f_w - 1) + 1)) / stride[1]
C
chengduoZH 已提交
33 34
    out = np.zeros((in_n, out_c, out_h, out_w))

武毅 已提交
35 36
    d_bolck_h = (dilation[0] * (f_h - 1) + 1)
    d_bolck_w = (dilation[1] * (f_w - 1) + 1)
C
chengduoZH 已提交
37

C
chengduoZH 已提交
38
    input_pad = np.pad(input, ((0, ), (0, ), (pad[0], ), (pad[1], )),
C
chengduoZH 已提交
39 40
                       mode='constant',
                       constant_values=0)
C
chengduoZH 已提交
41 42 43 44 45

    filter_dilation = np.zeros((out_c, f_c, d_bolck_h, d_bolck_w))
    filter_dilation[:, :, 0:d_bolck_h:dilation[0], 0:d_bolck_w:dilation[
        1]] = filter

C
chengduoZH 已提交
46 47 48
    for i in range(out_h):
        for j in range(out_w):
            for g in range(group):
C
chengduoZH 已提交
49 50
                input_pad_masked = \
                    input_pad[:, g * f_c:(g + 1) * f_c,
C
chengduoZH 已提交
51 52
                    i * stride[0]:i * stride[0] + d_bolck_h,
                    j * stride[1]:j * stride[1] + d_bolck_w]
C
chengduoZH 已提交
53

C
chengduoZH 已提交
54 55
                f_sub = filter_dilation[g * sub_out_c:(g + 1) *
                                        sub_out_c, :, :, :]
C
chengduoZH 已提交
56
                for k in range(sub_out_c):
C
chengduoZH 已提交
57 58 59
                    out[:, g * sub_out_c + k, i, j] = \
                        np.sum(input_pad_masked * f_sub[k, :, :, :],
                               axis=(1, 2, 3))
C
chengduoZH 已提交
60 61 62 63

    return out


H
hedaoyuan 已提交
64
class TestConv2dOp(OpTest):
65
    def setUp(self):
66
        self.use_cudnn = False
67
        self.use_mkldnn = False
C
chengduoZH 已提交
68 69
        self.init_op_type()
        self.init_group()
C
chengduoZH 已提交
70
        self.init_dilation()
K
Kexin Zhao 已提交
71
        self.init_data_type()
C
chengduoZH 已提交
72
        self.init_test_case()
C
chengduoZH 已提交
73

C
chengduoZH 已提交
74 75 76 77 78
        conv2d_param = {
            'stride': self.stride,
            'pad': self.pad,
            'dilation': self.dilations
        }
79

K
Kexin Zhao 已提交
80 81
        input = np.random.random(self.input_size).astype(self.dtype)
        filter = np.random.random(self.filter_size).astype(self.dtype)
K
Kexin Zhao 已提交
82
        output = conv2d_forward_naive(input, filter, self.groups,
K
Kexin Zhao 已提交
83 84 85 86 87 88 89 90
                                      conv2d_param).astype(self.dtype)

        # numpy float16 is binded to paddle::platform::float16 
        # in tensor_py.h via the help of numpy uint16 because
        # the internal memory representation of float16 is 
        # uint16_t in paddle or np.uint16 in numpy, which are
        # themselves binded together.        
        self.inputs = {
K
Kexin Zhao 已提交
91 92 93 94 95 96
            #'Input': (input.view(np.uint16)
            #          if self.dtype == np.float16 else input),
            #'Filter': (filter.view(np.uint16)
            #          if self.dtype == np.float16 else filter)
            'Input': OpTest.create_view(input),
            'Filter': OpTest.create_view(filter)
K
Kexin Zhao 已提交
97
        }
H
hedaoyuan 已提交
98
        self.attrs = {
C
chengduoZH 已提交
99 100
            'strides': self.stride,
            'paddings': self.pad,
C
chengduoZH 已提交
101
            'groups': self.groups,
102
            'dilations': self.dilations,
103 104
            'use_cudnn': self.use_cudnn,
            'use_mkldnn': self.use_mkldnn
H
hedaoyuan 已提交
105
        }
106 107
        self.outputs = {'Output': output}

H
hedaoyuan 已提交
108
    def test_check_output(self):
109 110 111 112 113
        if self.use_cudnn:
            place = core.CUDAPlace(0)
            self.check_output_with_place(place, atol=1e-5)
        else:
            self.check_output()
H
hedaoyuan 已提交
114

H
hedaoyuan 已提交
115
    def test_check_grad(self):
116 117 118 119 120 121 122 123 124 125
        if self.use_cudnn:
            place = core.CUDAPlace(0)
            self.check_grad_with_place(
                place,
                set(['Input', 'Filter']),
                'Output',
                max_relative_error=0.02)
        else:
            self.check_grad(
                set(['Input', 'Filter']), 'Output', max_relative_error=0.02)
H
hedaoyuan 已提交
126

127
    def test_check_grad_no_filter(self):
128 129 130 131 132 133 134 135 136 137 138 139 140
        if self.use_cudnn:
            place = core.CUDAPlace(0)
            self.check_grad_with_place(
                place, ['Input'],
                'Output',
                max_relative_error=0.02,
                no_grad_set=set(['Filter']))
        else:
            self.check_grad(
                ['Input'],
                'Output',
                max_relative_error=0.02,
                no_grad_set=set(['Filter']))
141 142

    def test_check_grad_no_input(self):
143 144 145 146 147 148 149 150 151 152 153 154 155
        if self.use_cudnn:
            place = core.CUDAPlace(0)
            self.check_grad_with_place(
                place, ['Filter'],
                'Output',
                max_relative_error=0.02,
                no_grad_set=set(['Input']))
        else:
            self.check_grad(
                ['Filter'],
                'Output',
                max_relative_error=0.02,
                no_grad_set=set(['Input']))
156

C
chengduoZH 已提交
157 158 159 160 161 162 163 164
    def init_test_case(self):
        self.pad = [0, 0]
        self.stride = [1, 1]
        self.input_size = [2, 3, 5, 5]  # NCHW
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 3, 3]

K
Kexin Zhao 已提交
165 166 167
    def init_data_type(self):
        self.dtype = np.float32

C
chengduoZH 已提交
168 169 170
    def init_dilation(self):
        self.dilations = [1, 1]

C
chengduoZH 已提交
171
    def init_group(self):
H
hedaoyuan 已提交
172 173
        self.groups = 1

C
chengduoZH 已提交
174
    def init_op_type(self):
武毅 已提交
175 176
        self.op_type = "conv2d"

H
hedaoyuan 已提交
177

C
chengduoZH 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
class TestWithPad(TestConv2dOp):
    def init_test_case(self):
        self.pad = [1, 1]
        self.stride = [1, 1]
        self.input_size = [2, 3, 5, 5]  # NCHW
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 3, 3]


class TestWithStride(TestConv2dOp):
    def init_test_case(self):
        self.pad = [1, 1]
        self.stride = [2, 2]
        self.input_size = [2, 3, 6, 6]  # NCHW
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 3, 3]


H
hedaoyuan 已提交
198
class TestWithGroup(TestConv2dOp):
C
chengduoZH 已提交
199
    def init_group(self):
H
hedaoyuan 已提交
200 201
        self.groups = 3

武毅 已提交
202

C
chengduoZH 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215
class TestWith1x1(TestConv2dOp):
    def init_test_case(self):
        self.pad = [0, 0]
        self.stride = [1, 1]
        self.input_size = [2, 3, 5, 5]  # NCHW
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 1, 1]

    def init_group(self):
        self.groups = 3


C
chengduoZH 已提交
216 217 218 219 220 221 222 223
class TestWithDilation(TestConv2dOp):
    def init_test_case(self):
        self.pad = [0, 0]
        self.stride = [1, 1]
        self.input_size = [2, 3, 10, 10]  # NCHW
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 3, 3]
C
chengduoZH 已提交
224

C
chengduoZH 已提交
225 226
    def init_dilation(self):
        self.dilations = [2, 2]
C
chengduoZH 已提交
227

C
chengduoZH 已提交
228
    def init_group(self):
C
chengduoZH 已提交
229
        self.groups = 3
武毅 已提交
230

C
chengduoZH 已提交
231

232 233 234 235 236 237 238 239 240 241 242 243 244
class TestWithInput1x1Filter1x1(TestConv2dOp):
    def init_test_case(self):
        self.pad = [0, 0]
        self.stride = [1, 1]
        self.input_size = [2, 3, 1, 1]  # NCHW
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 1, 1]

    def init_group(self):
        self.groups = 3


245 246
#----------------Conv2dCUDNN----------------
class TestCUDNN(TestConv2dOp):
C
chengduoZH 已提交
247
    def init_op_type(self):
248 249
        self.use_cudnn = True
        self.op_type = "conv2d"
C
chengduoZH 已提交
250 251


K
Kexin Zhao 已提交
252 253 254 255 256 257 258 259
class TestFP16CUDNN(TestCUDNN):
    def init_data_type(self):
        self.dtype = np.float16

    def test_check_output(self):
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
            if core.is_float16_supported(place):
K
Kexin Zhao 已提交
260
                self.check_output_with_place(place, atol=2e-2)
K
Kexin Zhao 已提交
261 262 263 264 265 266 267 268 269 270 271

    def test_check_grad(self):
        pass

    def test_check_grad_no_filter(self):
        pass

    def test_check_grad_no_input(self):
        pass


272
class TestCUDNNWithPad(TestWithPad):
C
chengduoZH 已提交
273
    def init_op_type(self):
274 275
        self.use_cudnn = True
        self.op_type = "conv2d"
C
chengduoZH 已提交
276 277


278
class TestCUDNNWithStride(TestWithStride):
C
chengduoZH 已提交
279
    def init_op_type(self):
280 281
        self.use_cudnn = True
        self.op_type = "conv2d"
武毅 已提交
282

C
chengduoZH 已提交
283

284
class TestCUDNNWithGroup(TestWithGroup):
C
chengduoZH 已提交
285
    def init_op_type(self):
286 287
        self.use_cudnn = True
        self.op_type = "conv2d"
C
chengduoZH 已提交
288

武毅 已提交
289

290
class TestCUDNNWith1x1(TestWith1x1):
C
chengduoZH 已提交
291
    def init_op_type(self):
292 293
        self.use_cudnn = True
        self.op_type = "conv2d"
C
chengduoZH 已提交
294

武毅 已提交
295

296 297 298 299 300 301
class TestCUDNNWithInput1x1Filter1x1(TestWithInput1x1Filter1x1):
    def init_op_type(self):
        self.use_cudnn = True
        self.op_type = "conv2d"


302 303 304 305 306 307 308 309 310
class TestDepthwiseConv(TestConv2dOp):
    def init_test_case(self):
        self.pad = [1, 1]
        self.stride = [2, 2]
        self.input_size = [2, 3, 5, 5]  # NCHW
        self.groups = 3
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 3, 3]
311
        self.op_type = "depthwise_conv2d"
312 313 314 315 316 317 318 319 320 321 322


class TestDepthwiseConv2(TestConv2dOp):
    def init_test_case(self):
        self.pad = [1, 1]
        self.stride = [1, 1]
        self.input_size = [2, 3, 5, 5]  # NCHW
        self.groups = 3
        assert np.mod(self.input_size[1], self.groups) == 0
        f_c = self.input_size[1] / self.groups
        self.filter_size = [6, f_c, 3, 3]
323
        self.op_type = "depthwise_conv2d"
324 325


326 327
# Please Don't remove the following code.
# Currently, CI use cudnn V5.0 which not support dilation conv.
328
# class TestCUDNNWithDilation(TestWithDilation):
C
chengduoZH 已提交
329 330 331
#     def init_op_type(self):
#         self.op_type = "conv_cudnn"

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

#----------------Conv2dMKLDNN----------------
class TestMKLDNN(TestConv2dOp):
    def init_op_type(self):
        self.use_mkldnn = True
        self.op_type = "conv2d"


class TestMKLDNNWithPad(TestWithPad):
    def init_op_type(self):
        self.use_mkldnn = True
        self.op_type = "conv2d"


class TestMKLDNNWithStride(TestWithStride):
    def init_op_type(self):
        self.use_mkldnn = True
        self.op_type = "conv2d"


352 353
if __name__ == '__main__':
    unittest.main()