test_prelu_op.py 10.1 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
from __future__ import print_function

Z
zchen0211 已提交
17 18
import unittest
import numpy as np
19
import paddle.fluid as fluid
M
minqiyang 已提交
20
import six
21
import paddle.fluid.core as core
22
from paddle.fluid import Program, program_guard
23
from op_test import OpTest, skip_check_grad_ci
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
import paddle
import paddle.nn.functional as F


def ref_prelu(x, weight):
    x_t = x.copy()
    weight = weight.reshape(1, -1, 1, 1)
    neg_indices = x <= 0
    assert x.shape == neg_indices.shape
    x_t[neg_indices] = (x_t * weight)[neg_indices]
    return (x_t, )


def ref_prelu_nn(x, num_parameters, init):
    weight_np = np.full((num_parameters), init)
    return ref_prelu(x, weight_np)


class TestFunctionalPReluAPI(unittest.TestCase):
    def setUp(self):
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda(
        ) else paddle.CPUPlace()
        self.x_np = np.random.uniform(-1., 1., [1, 2, 3, 4]).astype('float32')
        self.weight_np_0 = np.random.randn(1).astype('float32')
        self.weight_np_1 = np.random.randn(self.x_np.shape[1]).astype('float32')

    def static_check(self, weight_np):
        with paddle.static.program_guard(paddle.static.Program()):
52 53
            x = paddle.fluid.data('X', self.x_np.shape, 'float32')
            weight = paddle.fluid.data('Alpha', weight_np.shape, 'float32')
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
            out = F.prelu(x, weight)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np,
                                'Alpha': weight_np},
                          fetch_list=[out])
        out_ref = ref_prelu(self.x_np, weight_np)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def dygraph_check(self, weight_np):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        weight = paddle.to_tensor(weight_np)
        out = F.prelu(x, weight)
        out_ref = ref_prelu(self.x_np, weight_np)
        self.assertEqual(np.allclose(out_ref, out.numpy()), True)
        paddle.enable_static()

    def test_static_api(self):
        self.static_check(self.weight_np_0)
        self.static_check(self.weight_np_1)
Z
zchen0211 已提交
74

75 76 77
    def test_dygraph_api(self):
        self.dygraph_check(self.weight_np_0)
        self.dygraph_check(self.weight_np_1)
Z
zchen0211 已提交
78

79 80
    def test_error(self):
        with paddle.static.program_guard(paddle.static.Program()):
81
            weight_fp32 = paddle.fluid.data(
82
                name='weight_fp32', shape=[1], dtype='float32')
83
            # The input type must be Variable.
84
            self.assertRaises(TypeError, F.prelu, x=1, weight=weight_fp32)
85
            # The input dtype must be float16, float32, float64.
86
            x_int32 = paddle.fluid.data(name='x_int32', shape=[2, 3], dtype='int32')
87 88
            self.assertRaises(TypeError, F.prelu, x=x_int32, weight=weight_fp32)
            # support the input dtype is float16
89
            x_fp16 = paddle.fluid.data(name='x_fp16', shape=[2, 3], dtype='float16')
90 91 92 93 94 95 96 97 98 99 100 101 102
            F.prelu(x=x_fp16, weight=weight_fp32)


class TestNNPReluAPI(unittest.TestCase):
    def setUp(self):
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda(
        ) else paddle.CPUPlace()
        self.x_np = np.ones([1, 2, 3, 4]).astype('float32')

    def test_static_api(self):
        startup_program = paddle.static.Program()
        train_program = paddle.static.Program()
        with paddle.static.program_guard(train_program, startup_program):
103
            x = paddle.fluid.data(name='X', shape=self.x_np.shape, dtype='float32')
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
            m = paddle.nn.PReLU()
            out = m(x)
            exe = paddle.static.Executor(self.place)
            exe.run(startup_program)
            res = exe.run(train_program,
                          feed={'X': self.x_np},
                          fetch_list=[out])
        out_ref = ref_prelu_nn(self.x_np, 1, 0.25)
        self.assertEqual(np.allclose(out_ref, res[0]), True)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)

        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.PReLU()
        out = m(x)
        out_ref = ref_prelu_nn(self.x_np, 1, 0.25)
        self.assertEqual(np.allclose(out_ref, out.numpy()), True)

        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.PReLU(num_parameters=self.x_np.shape[1])
        out = m(x)
        out_ref = ref_prelu_nn(self.x_np, self.x_np.shape[1], 0.25)
        self.assertEqual(np.allclose(out_ref, out.numpy()), True)

        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.PReLU(init=0.5)
        out = m(x)
        out_ref = ref_prelu_nn(self.x_np, 1, 0.5)
        self.assertEqual(np.allclose(out_ref, out.numpy()), True)

        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.PReLU(weight_attr=fluid.ParamAttr(name="weight"))
        out = m(x)
        out_ref = ref_prelu_nn(self.x_np, 1, 0.25)
        self.assertEqual(np.allclose(out_ref, out.numpy()), True)

        x = paddle.to_tensor(self.x_np)
        m = paddle.nn.PReLU(weight_attr=fluid.ParamAttr(
            initializer=fluid.initializer.Constant(0.5)))
        out = m(x)
        out_ref = ref_prelu_nn(self.x_np, 1, 0.5)
        self.assertEqual(np.allclose(out_ref, out.numpy()), True)

        paddle.enable_static()
149 150


Z
zchen0211 已提交
151
class PReluTest(OpTest):
Z
zchen0211 已提交
152
    def setUp(self):
153 154
        self.init_input_shape()
        self.init_attr()
Z
zchen0211 已提交
155
        self.op_type = "prelu"
J
jerrywgz 已提交
156

157
        x_np = np.random.uniform(-1, 1, self.x_shape)
J
jerrywgz 已提交
158 159 160 161 162
        # Since zero point in prelu is not differentiable, avoid randomize
        # zero.
        x_np[np.abs(x_np) < 0.005] = 0.02

        if self.attrs == {'mode': "all"}:
163
            alpha_np = np.random.uniform(-1, -0.5, (1))
J
jerrywgz 已提交
164
        elif self.attrs == {'mode': "channel"}:
165
            alpha_np = np.random.uniform(-1, -0.5, [1, self.x_shape[1], 1, 1])
J
jerrywgz 已提交
166
        else:
167 168
            alpha_np = np.random.uniform(-1, -0.5, [1] + self.x_shape[1:])

169
        self.inputs = {'X': x_np, 'Alpha': alpha_np}
J
jerrywgz 已提交
170

171 172 173
        # NOTE(zhiqu): reshape inputs['Alpha'] from [1, 100, 1, 1] to [1, 100] + [1]*len(x.shape[2:])
        # since np operands could not be broadcast together with shapes (1,100,2,2,2,3) (1,100,1,1) 	
        reshaped_alpha = self.inputs['Alpha']
174
        if self.attrs == {'mode': "channel"}:
175
            reshaped_alpha = np.reshape(
176 177 178
                self.inputs['Alpha'],
                [1, self.x_shape[1]] + [1] * len(self.x_shape[2:]))

Z
zchen0211 已提交
179
        out_np = np.maximum(self.inputs['X'], 0.)
180
        out_np = out_np + np.minimum(self.inputs['X'], 0.) * reshaped_alpha
Z
zchen0211 已提交
181 182
        assert out_np is not self.inputs['X']
        self.outputs = {'Out': out_np}
Z
zchen0211 已提交
183

184
    def init_input_shape(self):
185
        self.x_shape = [2, 100, 3, 4]
186 187

    def init_attr(self):
J
jerrywgz 已提交
188 189
        self.attrs = {'mode': "channel"}

190
    def test_check_output(self):
Z
zchen0211 已提交
191 192
        self.check_output()

193
    def test_check_grad(self):
194
        self.check_grad(['X', 'Alpha'], 'Out')
J
jerrywgz 已提交
195 196


197 198 199 200 201
@skip_check_grad_ci(
    reason="[skip shape check] Input(Alpha) must be 1-D and only has one data in 'all' mode"
)
class TestModeAll(PReluTest):
    def init_input_shape(self):
202
        self.x_shape = [2, 3, 4, 5]
M
minqiyang 已提交
203

204 205
    def init_attr(self):
        self.attrs = {'mode': "all"}
M
minqiyang 已提交
206

Z
zchen0211 已提交
207

208 209
class TestModeElt(PReluTest):
    def init_input_shape(self):
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
        self.x_shape = [3, 2, 5, 10]

    def init_attr(self):
        self.attrs = {'mode': "element"}


@skip_check_grad_ci(
    reason="[skip shape check] Input(Alpha) must be 1-D and only has one data in 'all' mode"
)
class TestModeAllRank3(PReluTest):
    def init_input_shape(self):
        self.x_shape = [1, 200, 3]

    def init_attr(self):
        self.attrs = {'mode': "all"}


@skip_check_grad_ci(
    reason="[skip shape check] Input(Alpha) must be 1-D and only has one data in 'all' mode"
)
class TestModeAllRank6(PReluTest):
    def init_input_shape(self):
        self.x_shape = [1, 2, 3, 4, 5, 6]

    def init_attr(self):
        self.attrs = {'mode': "all"}


class TestModeChannelRank3(PReluTest):
    def init_input_shape(self):
        self.x_shape = [1, 200, 3]

    def init_attr(self):
        self.attrs = {'mode': "channel"}


class TestModeChannelRank6(PReluTest):
    def init_input_shape(self):
        self.x_shape = [1, 100, 2, 2, 2, 2]

    def init_attr(self):
        self.attrs = {'mode': "channel"}


class TestModeElementRank3(PReluTest):
    def init_input_shape(self):
        self.x_shape = [3, 10, 10]

    def init_attr(self):
        self.attrs = {'mode': "element"}


class TestModeElementRank6(PReluTest):
    def init_input_shape(self):
        self.x_shape = [3, 2, 2, 4, 5, 2]
Z
zchen0211 已提交
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
    def init_attr(self):
        self.attrs = {'mode': "element"}


def prelu_t(x, mode, param_attr=None, name=None):
    helper = fluid.layer_helper.LayerHelper('prelu', **locals())
    alpha_shape = [1, x.shape[1], 1, 1]
    dtype = helper.input_dtype(input_param_name='x')
    alpha = helper.create_parameter(
        attr=helper.param_attr,
        shape=alpha_shape,
        dtype='float32',
        is_bias=False,
        default_initializer=fluid.initializer.ConstantInitializer(0.25))
    out = helper.create_variable_for_type_inference(dtype)
    helper.append_op(
        type="prelu",
        inputs={"X": x,
                'Alpha': alpha},
        attrs={"mode": mode},
        outputs={"Out": out})
    return out


# error message test if mode is not one of 'all', 'channel', 'element'
class TestModeError(unittest.TestCase):
    def test_mode_error(self):
        main_program = Program()
        with fluid.program_guard(main_program, Program()):
            x = fluid.data(name='x', shape=[2, 3, 4, 5])
            try:
                y = prelu_t(x, 'any')
            except Exception as e:
                assert (e.args[0].find('InvalidArgumentError') != -1)
300 301


Z
zchen0211 已提交
302 303
if __name__ == "__main__":
    unittest.main()