test_maxout_op.py 4.6 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.

W
wanghaox 已提交
15
import unittest
16

W
wanghaox 已提交
17
import numpy as np
18 19
from op_test import OpTest

20
import paddle
21
import paddle.fluid.core as core
22
import paddle.nn.functional as F
23
from paddle.fluid.framework import _test_eager_guard
W
wanghaox 已提交
24

25 26
paddle.enable_static()
np.random.seed(1)
W
wanghaox 已提交
27

28 29 30 31

def maxout_forward_naive(x, groups, channel_axis):
    s0, s1, s2, s3 = x.shape
    if channel_axis == 1:
32 33 34 35 36 37
        return np.ndarray(
            [s0, s1 // groups, groups, s2, s3], buffer=x, dtype=x.dtype
        ).max(axis=2)
    return np.ndarray(
        [s0, s1, s2, s3 // groups, groups], buffer=x, dtype=x.dtype
    ).max(axis=4)
W
wanghaox 已提交
38 39 40 41 42


class TestMaxOutOp(OpTest):
    def setUp(self):
        self.op_type = "maxout"
43
        self.python_api = paddle.nn.functional.maxout
44 45 46 47 48 49 50 51
        self.dtype = 'float64'
        self.shape = [3, 6, 2, 4]
        self.groups = 2
        self.axis = 1
        self.set_attrs()

        x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
        out = maxout_forward_naive(x, self.groups, self.axis)
W
wanghaox 已提交
52

53
        self.inputs = {'X': x}
54
        self.attrs = {'groups': self.groups, 'axis': self.axis}
55
        self.outputs = {'Out': out}
W
wanghaox 已提交
56

57 58
    def set_attrs(self):
        pass
W
wanghaox 已提交
59 60

    def test_check_output(self):
61
        self.check_output(check_eager=True)
W
wanghaox 已提交
62 63

    def test_check_grad(self):
64
        self.check_grad(['X'], 'Out', check_eager=True)
W
wanghaox 已提交
65

66

67 68 69
class TestMaxOutOpAxis0(TestMaxOutOp):
    def set_attrs(self):
        self.axis = -1
70 71


72 73 74
class TestMaxOutOpAxis1(TestMaxOutOp):
    def set_attrs(self):
        self.axis = 3
75 76


77 78 79
class TestMaxOutOpFP32(TestMaxOutOp):
    def set_attrs(self):
        self.dtype = 'float32'
80 81


82 83 84
class TestMaxOutOpGroups(TestMaxOutOp):
    def set_attrs(self):
        self.groups = 3
85

W
wanghaox 已提交
86

87 88 89 90 91 92
class TestMaxoutAPI(unittest.TestCase):
    # test paddle.nn.Maxout, paddle.nn.functional.maxout
    def setUp(self):
        self.x_np = np.random.uniform(-1, 1, [2, 6, 5, 4]).astype(np.float64)
        self.groups = 2
        self.axis = 1
93 94 95
        self.place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
96
            else paddle.CPUPlace()
97
        )
98 99 100

    def test_static_api(self):
        with paddle.static.program_guard(paddle.static.Program()):
101
            x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
102 103 104 105 106 107 108
            out1 = F.maxout(x, self.groups, self.axis)
            m = paddle.nn.Maxout(self.groups, self.axis)
            out2 = m(x)
            exe = paddle.static.Executor(self.place)
            res = exe.run(feed={'X': self.x_np}, fetch_list=[out1, out2])
        out_ref = maxout_forward_naive(self.x_np, self.groups, self.axis)
        for r in res:
109
            np.testing.assert_allclose(out_ref, r, rtol=1e-05)
110

111
    def func_test_dygraph_api(self):
112 113 114 115 116 117 118
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        out1 = F.maxout(x, self.groups, self.axis)
        m = paddle.nn.Maxout(self.groups, self.axis)
        out2 = m(x)
        out_ref = maxout_forward_naive(self.x_np, self.groups, self.axis)
        for r in [out1, out2]:
119
            np.testing.assert_allclose(out_ref, r.numpy(), rtol=1e-05)
120 121 122

        out3 = F.maxout(x, self.groups, -1)
        out3_ref = maxout_forward_naive(self.x_np, self.groups, -1)
123
        np.testing.assert_allclose(out3_ref, out3.numpy(), rtol=1e-05)
124 125
        paddle.enable_static()

126
    def test_errors(self):
127
        with paddle.static.program_guard(paddle.static.Program()):
128
            # The input type must be Variable.
129
            self.assertRaises(TypeError, F.maxout, 1)
130
            # The input dtype must be float16, float32, float64.
131 132 133
            x_int32 = paddle.fluid.data(
                name='x_int32', shape=[2, 4, 6, 8], dtype='int32'
            )
134 135
            self.assertRaises(TypeError, F.maxout, x_int32)

136
            x_float32 = paddle.fluid.data(name='x_float32', shape=[2, 4, 6, 8])
137
            self.assertRaises(ValueError, F.maxout, x_float32, 2, 2)
138

139
    def test_dygraph_api(self):
140
        with _test_eager_guard():
141 142
            self.func_test_dygraph_api()
        self.func_test_dygraph_api()
143

144

W
wanghaox 已提交
145 146
if __name__ == '__main__':
    unittest.main()