test_conv1d_layer.py 7.5 KB
Newer Older
W
whs 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

import numpy as np
import paddle
from paddle import fluid, nn
import paddle.fluid.dygraph as dg
import paddle.nn.functional as F
import paddle.fluid.initializer as I
import unittest


C
cnn 已提交
24
class Conv1DTestCase(unittest.TestCase):
W
whs 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
    def __init__(self,
                 methodName='runTest',
                 batch_size=4,
                 spartial_shape=(16, ),
                 num_channels=6,
                 num_filters=8,
                 filter_size=3,
                 padding=0,
                 padding_mode="zeros",
                 stride=1,
                 dilation=1,
                 groups=1,
                 no_bias=False,
                 dtype="float32",
                 data_format="NCL"):
C
cnn 已提交
40
        super(Conv1DTestCase, self).__init__(methodName)
W
whs 已提交
41 42 43 44 45 46
        self.batch_size = batch_size
        self.num_channels = num_channels
        self.num_filters = num_filters
        self.spartial_shape = spartial_shape
        self.filter_size = filter_size
        self.data_format = data_format
L
LielinJiang 已提交
47
        self.channel_last = (self.data_format == "NLC")
W
whs 已提交
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

        self.padding = padding
        self.padding_mode = padding_mode
        self.stride = stride
        self.dilation = dilation
        self.groups = groups
        self.no_bias = no_bias
        self.dtype = dtype

    def setUp(self):
        input_shape = (self.batch_size, self.num_channels
                       ) + self.spartial_shape if not self.channel_last else (
                           self.batch_size, ) + self.spartial_shape + (
                               self.num_channels, )
        self.input = np.random.randn(*input_shape).astype(self.dtype)

        if isinstance(self.filter_size, int):
            filter_size = [self.filter_size]
        else:
            filter_size = self.filter_size
        self.weight_shape = weight_shape = (self.num_filters, self.num_channels
                                            // self.groups) + tuple(filter_size)
        self.weight = np.random.uniform(
            -1, 1, size=weight_shape).astype(self.dtype)
        if not self.no_bias:
            self.bias = np.random.uniform(
                -1, 1, size=(self.num_filters, )).astype(self.dtype)
        else:
            self.bias = None

    def functional(self, place):
        main = fluid.Program()
        start = fluid.Program()
        with fluid.unique_name.guard():
            with fluid.program_guard(main, start):
                input_shape = (-1, self.num_channels,
                               -1) if not self.channel_last else (
                                   -1, -1, self.num_channels)
                x_var = fluid.data("input", input_shape, dtype=self.dtype)
                w_var = fluid.data(
                    "weight", self.weight_shape, dtype=self.dtype)
                b_var = fluid.data(
                    "bias", (self.num_filters, ), dtype=self.dtype)
                y_var = F.conv1d(
                    x_var,
                    w_var,
                    b_var if not self.no_bias else None,
                    padding=self.padding,
                    stride=self.stride,
                    dilation=self.dilation,
                    groups=self.groups,
                    data_format=self.data_format)
        feed_dict = {"input": self.input, "weight": self.weight}
        if self.bias is not None:
            feed_dict["bias"] = self.bias
        exe = fluid.Executor(place)
        exe.run(start)
        y_np, = exe.run(main, feed=feed_dict, fetch_list=[y_var])
        return y_np

    def paddle_nn_layer(self):
        x_var = paddle.to_tensor(self.input)
C
cnn 已提交
110
        conv = nn.Conv1D(
W
whs 已提交
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
            self.num_channels,
            self.num_filters,
            self.filter_size,
            padding=self.padding,
            padding_mode=self.padding_mode,
            stride=self.stride,
            dilation=self.dilation,
            groups=self.groups,
            data_format=self.data_format)
        conv.weight.set_value(self.weight)
        if not self.no_bias:
            conv.bias.set_value(self.bias)
        y_var = conv(x_var)
        y_np = y_var.numpy()
        return y_np

    def _test_equivalence(self, place):
        result1 = self.functional(place)
        with dg.guard(place):
            result2 = self.paddle_nn_layer()
        np.testing.assert_array_almost_equal(result1, result2)

    def runTest(self):
        place = fluid.CPUPlace()
        self._test_equivalence(place)

        if fluid.core.is_compiled_with_cuda():
            place = fluid.CUDAPlace(0)
            self._test_equivalence(place)


C
cnn 已提交
142
class Conv1DErrorTestCase(Conv1DTestCase):
W
whs 已提交
143 144 145 146 147 148 149
    def runTest(self):
        place = fluid.CPUPlace()
        with dg.guard(place):
            with self.assertRaises(ValueError):
                self.paddle_nn_layer()


C
cnn 已提交
150
class Conv1DTypeErrorTestCase(Conv1DTestCase):
L
LielinJiang 已提交
151 152 153 154 155 156 157
    def runTest(self):
        place = fluid.CPUPlace()
        with dg.guard(place):
            with self.assertRaises(TypeError):
                self.paddle_nn_layer()


W
whs 已提交
158
def add_cases(suite):
C
cnn 已提交
159 160 161
    suite.addTest(Conv1DTestCase(methodName='runTest'))
    suite.addTest(Conv1DTestCase(methodName='runTest', stride=[1], dilation=2))
    suite.addTest(Conv1DTestCase(methodName='runTest', stride=2, dilation=(1)))
W
whs 已提交
162
    suite.addTest(
C
cnn 已提交
163
        Conv1DTestCase(
W
whs 已提交
164 165
            methodName='runTest', padding="same", no_bias=True))
    suite.addTest(
C
cnn 已提交
166
        Conv1DTestCase(
W
whs 已提交
167 168
            methodName='runTest', filter_size=3, padding='valid'))
    suite.addTest(
C
cnn 已提交
169
        Conv1DTestCase(
W
whs 已提交
170
            methodName='runTest', padding=2, data_format='NLC'))
C
cnn 已提交
171 172 173 174
    suite.addTest(Conv1DTestCase(methodName='runTest', padding=[1]))
    suite.addTest(Conv1DTestCase(methodName='runTest', padding=[1, 2]))
    suite.addTest(Conv1DTestCase(methodName='runTest', padding=2))
    suite.addTest(Conv1DTestCase(methodName='runTest'))
W
whs 已提交
175
    suite.addTest(
C
cnn 已提交
176
        Conv1DTestCase(
W
whs 已提交
177 178
            methodName='runTest', groups=2, padding="valid"))
    suite.addTest(
C
cnn 已提交
179
        Conv1DTestCase(
W
whs 已提交
180 181 182 183 184 185 186 187 188 189
            methodName='runTest',
            num_filters=6,
            num_channels=3,
            groups=3,
            padding="valid",
            data_format='NLC'))


def add_error_cases(suite):
    suite.addTest(
C
cnn 已提交
190
        Conv1DTypeErrorTestCase(
W
whs 已提交
191 192
            methodName='runTest', padding_mode="reflect", padding="valid"))
    suite.addTest(
C
cnn 已提交
193
        Conv1DErrorTestCase(
W
whs 已提交
194 195
            methodName='runTest', data_format="VALID"))
    suite.addTest(
C
cnn 已提交
196
        Conv1DErrorTestCase(
W
whs 已提交
197 198
            methodName='runTest', padding_mode="VALID"))
    suite.addTest(
C
cnn 已提交
199
        Conv1DErrorTestCase(
W
whs 已提交
200 201
            methodName='runTest', num_channels=5, groups=2))
    suite.addTest(
C
cnn 已提交
202
        Conv1DErrorTestCase(
W
whs 已提交
203 204
            methodName='runTest', num_filters=8, num_channels=15, groups=3))
    suite.addTest(
C
cnn 已提交
205
        Conv1DErrorTestCase(
W
whs 已提交
206 207 208 209 210 211 212 213 214 215 216 217
            methodName='runTest', padding=[1, 2, 3, 4, 5]))


def load_tests(loader, standard_tests, pattern):
    suite = unittest.TestSuite()
    add_cases(suite)
    add_error_cases(suite)
    return suite


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