test_expand_op.py 8.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

Y
yangyaming 已提交
17 18
import unittest
import numpy as np
19
from op_test import OpTest
L
liym27 已提交
20
import paddle.fluid as fluid
W
wangchaochaohu 已提交
21
from paddle.fluid import compiler, Program, program_guard
P
pangyoki 已提交
22
import paddle
Y
yangyaming 已提交
23 24


L
liym27 已提交
25
# Situation 1: expand_times is a list(without tensor)
Y
yangyaming 已提交
26 27 28
class TestExpandOpRank1(OpTest):
    def setUp(self):
        self.op_type = "expand"
L
liym27 已提交
29 30
        self.init_data()

31
        self.inputs = {'X': np.random.random(self.ori_shape).astype("float64")}
L
liym27 已提交
32 33
        self.attrs = {'expand_times': self.expand_times}
        output = np.tile(self.inputs['X'], self.expand_times)
Y
yangyaming 已提交
34 35
        self.outputs = {'Out': output}

L
liym27 已提交
36
    def init_data(self):
37
        self.ori_shape = [100]
L
liym27 已提交
38 39
        self.expand_times = [2]

Y
yangyaming 已提交
40 41 42 43 44 45 46
    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


L
liym27 已提交
47 48
class TestExpandOpRank2_Corner(TestExpandOpRank1):
    def init_data(self):
Z
zhupengyang 已提交
49
        self.ori_shape = [120]
L
liym27 已提交
50
        self.expand_times = [2]
51 52


L
liym27 已提交
53 54 55 56
class TestExpandOpRank2(TestExpandOpRank1):
    def init_data(self):
        self.ori_shape = [12, 14]
        self.expand_times = [2, 3]
57 58


L
liym27 已提交
59 60
class TestExpandOpRank3_Corner(TestExpandOpRank1):
    def init_data(self):
Z
zhupengyang 已提交
61
        self.ori_shape = (2, 10, 5)
L
liym27 已提交
62
        self.expand_times = (1, 1, 1)
Y
yangyaming 已提交
63 64


L
liym27 已提交
65 66
class TestExpandOpRank3(TestExpandOpRank1):
    def init_data(self):
Z
zhupengyang 已提交
67
        self.ori_shape = (2, 4, 15)
L
liym27 已提交
68 69
        self.expand_times = (2, 1, 4)

Y
yangyaming 已提交
70

L
liym27 已提交
71 72 73 74
class TestExpandOpRank4(TestExpandOpRank1):
    def init_data(self):
        self.ori_shape = (2, 4, 5, 7)
        self.expand_times = (3, 2, 1, 2)
Y
yangyaming 已提交
75

L
liym27 已提交
76 77 78

# Situation 2: expand_times is a list(with tensor)
class TestExpandOpRank1_tensor_attr(OpTest):
79 80
    def setUp(self):
        self.op_type = "expand"
L
liym27 已提交
81 82 83 84 85 86
        self.init_data()
        expand_times_tensor = []
        for index, ele in enumerate(self.expand_times):
            expand_times_tensor.append(("x" + str(index), np.ones(
                (1)).astype('int32') * ele))

87
        self.inputs = {
88
            'X': np.random.random(self.ori_shape).astype("float64"),
L
liym27 已提交
89
            'expand_times_tensor': expand_times_tensor,
90
        }
L
liym27 已提交
91 92
        self.attrs = {"expand_times": self.infer_expand_times}
        output = np.tile(self.inputs['X'], self.expand_times)
93 94
        self.outputs = {'Out': output}

L
liym27 已提交
95
    def init_data(self):
Z
zhupengyang 已提交
96
        self.ori_shape = [100]
L
liym27 已提交
97 98 99
        self.expand_times = [2]
        self.infer_expand_times = [-1]

100 101 102 103 104 105 106
    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


L
liym27 已提交
107 108 109 110 111
class TestExpandOpRank2_Corner_tensor_attr(TestExpandOpRank1_tensor_attr):
    def init_data(self):
        self.ori_shape = [12, 14]
        self.expand_times = [1, 1]
        self.infer_expand_times = [1, -1]
Y
yangyaming 已提交
112 113


L
liym27 已提交
114 115 116 117 118
class TestExpandOpRank2_attr_tensor(TestExpandOpRank1_tensor_attr):
    def init_data(self):
        self.ori_shape = [12, 14]
        self.expand_times = [2, 3]
        self.infer_expand_times = [-1, 3]
Y
yangyaming 已提交
119 120


L
liym27 已提交
121 122
# Situation 3: expand_times is a tensor
class TestExpandOpRank1_tensor(OpTest):
123 124
    def setUp(self):
        self.op_type = "expand"
L
liym27 已提交
125 126
        self.init_data()

127
        self.inputs = {
128
            'X': np.random.random(self.ori_shape).astype("float64"),
L
liym27 已提交
129
            'ExpandTimes': np.array(self.expand_times).astype("int32"),
130 131
        }
        self.attrs = {}
L
liym27 已提交
132
        output = np.tile(self.inputs['X'], self.expand_times)
133 134
        self.outputs = {'Out': output}

L
liym27 已提交
135
    def init_data(self):
Z
zhupengyang 已提交
136
        self.ori_shape = [100]
L
liym27 已提交
137
        self.expand_times = [2]
Y
yangyaming 已提交
138 139 140 141 142 143 144 145

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')


L
liym27 已提交
146 147 148 149
class TestExpandOpRank2_tensor(TestExpandOpRank1_tensor):
    def init_data(self):
        self.ori_shape = [12, 14]
        self.expand_times = [2, 3]
Y
yangyaming 已提交
150 151


L
liym27 已提交
152
# Situation 4: input x is Integer
153 154 155
class TestExpandOpInteger(OpTest):
    def setUp(self):
        self.op_type = "expand"
J
jerrywgz 已提交
156 157 158 159
        self.inputs = {
            'X': np.random.randint(
                10, size=(2, 4, 5)).astype("int32")
        }
160 161 162 163 164 165 166 167
        self.attrs = {'expand_times': [2, 1, 4]}
        output = np.tile(self.inputs['X'], (2, 1, 4))
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output()


L
liym27 已提交
168
# Situation 5: input x is Bool
169 170 171
class TestExpandOpBoolean(OpTest):
    def setUp(self):
        self.op_type = "expand"
J
jerrywgz 已提交
172
        self.inputs = {'X': np.random.randint(2, size=(2, 4, 5)).astype("bool")}
173 174 175 176 177 178 179 180
        self.attrs = {'expand_times': [2, 1, 4]}
        output = np.tile(self.inputs['X'], (2, 1, 4))
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output()


W
wangchaochaohu 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
# Situation 56: input x is Integer
class TestExpandOpInt64_t(OpTest):
    def setUp(self):
        self.op_type = "expand"
        self.inputs = {
            'X': np.random.randint(
                10, size=(2, 4, 5)).astype("int64")
        }
        self.attrs = {'expand_times': [2, 1, 4]}
        output = np.tile(self.inputs['X'], (2, 1, 4))
        self.outputs = {'Out': output}

    def test_check_output(self):
        self.check_output()


197
class TestExpandError(unittest.TestCase):
W
wangchaochaohu 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210
    def test_errors(self):
        with program_guard(Program(), Program()):
            x1 = fluid.create_lod_tensor(
                np.array([[-1]]), [[1]], fluid.CPUPlace())
            expand_times = [2, 2]
            self.assertRaises(TypeError, fluid.layers.expand, x1, expand_times)
            x2 = fluid.layers.data(name='x2', shape=[4], dtype="uint8")
            self.assertRaises(TypeError, fluid.layers.expand, x2, expand_times)
            x3 = fluid.layers.data(name='x3', shape=[4], dtype="bool")
            x3.stop_gradient = True
            self.assertRaises(ValueError, fluid.layers.expand, x3, expand_times)


L
liym27 已提交
211
# Test python API
212
class TestExpandAPI(unittest.TestCase):
L
liym27 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225
    def test_api(self):
        input = np.random.random([12, 14]).astype("float32")
        x = fluid.layers.data(
            name='x', shape=[12, 14], append_batch_size=False, dtype="float32")

        positive_2 = fluid.layers.fill_constant([1], "int32", 2)
        expand_times = fluid.layers.data(
            name="expand_times", shape=[2], append_batch_size=False)

        out_1 = fluid.layers.expand(x, expand_times=[2, 3])
        out_2 = fluid.layers.expand(x, expand_times=[positive_2, 3])
        out_3 = fluid.layers.expand(x, expand_times=expand_times)

L
liym27 已提交
226 227
        g0 = fluid.backward.calc_gradient(out_2, x)

L
liym27 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240
        exe = fluid.Executor(place=fluid.CPUPlace())
        res_1, res_2, res_3 = exe.run(fluid.default_main_program(),
                                      feed={
                                          "x": input,
                                          "expand_times":
                                          np.array([1, 3]).astype("int32")
                                      },
                                      fetch_list=[out_1, out_2, out_3])
        assert np.array_equal(res_1, np.tile(input, (2, 3)))
        assert np.array_equal(res_2, np.tile(input, (2, 3)))
        assert np.array_equal(res_3, np.tile(input, (1, 3)))


P
pangyoki 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254
class TestExpandDygraphAPI(unittest.TestCase):
    def test_expand_times_is_tensor(self):
        with paddle.fluid.dygraph.guard():
            a = paddle.rand([2, 5])
            b = paddle.fluid.layers.expand(a, expand_times=[2, 3])
            c = paddle.fluid.layers.expand(
                a, expand_times=paddle.to_tensor(
                    [2, 3], dtype='int32'))
            self.assertTrue(
                np.array_equal(b.numpy(), np.tile(a.numpy(), [2, 3])))
            self.assertTrue(
                np.array_equal(c.numpy(), np.tile(a.numpy(), [2, 3])))


Y
yangyaming 已提交
255 256
if __name__ == "__main__":
    unittest.main()