test_meshgrid_op.py 9.8 KB
Newer Older
S
suytingwan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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 unittest
16

S
suytingwan 已提交
17
import numpy as np
姜永久 已提交
18
from eager_op_test import OpTest
19

S
suytingwan 已提交
20
import paddle
21
from paddle import fluid
S
suytingwan 已提交
22 23


姜永久 已提交
24 25 26 27
def meshgrid_wrapper(x):
    return paddle.tensor.meshgrid(x[0], x[1])


S
suytingwan 已提交
28 29 30
class TestMeshgridOp(OpTest):
    def setUp(self):
        self.op_type = "meshgrid"
31
        self.prim_op_type = "comp"
姜永久 已提交
32
        self.python_api = meshgrid_wrapper
33
        self.public_python_api = meshgrid_wrapper
S
suytingwan 已提交
34 35 36 37 38 39
        self.dtype = self.get_dtype()
        ins, outs = self.init_test_data()
        self.inputs = {'X': [('x%d' % i, ins[i]) for i in range(len(ins))]}
        self.outputs = {
            'Out': [('out%d' % i, outs[i]) for i in range(len(outs))]
        }
姜永久 已提交
40
        self.python_out_sig = ['out0', 'out1']
41
        self.if_enable_cinn()
S
suytingwan 已提交
42 43 44 45 46

    def get_dtype(self):
        return "float64"

    def test_check_output(self):
47
        self.check_output(check_prim=True)
S
suytingwan 已提交
48 49

    def test_check_grad(self):
50
        self.check_grad(['x0'], ['out0', 'out1'], check_prim=True)
S
suytingwan 已提交
51 52 53 54 55 56

    def init_test_data(self):
        self.shape = self.get_x_shape()
        ins = []
        outs = []
        for i in range(len(self.shape)):
57
            ins.append(np.random.random((self.shape[i],)).astype(self.dtype))
S
suytingwan 已提交
58 59 60 61 62 63 64 65 66 67 68

        for i in range(len(self.shape)):
            out_reshape = [1] * len(self.shape)
            out_reshape[i] = self.shape[i]
            out_temp = np.reshape(ins[i], out_reshape)
            outs.append(np.broadcast_to(out_temp, self.shape))
        return ins, outs

    def get_x_shape(self):
        return [100, 200]

69
    def if_enable_cinn(self):
C
ccrrong 已提交
70 71
        # 拆解tile_grad导致cinn运行超时
        self.enable_cinn = False
72

S
suytingwan 已提交
73 74 75 76 77 78 79 80

class TestMeshgridOp2(TestMeshgridOp):
    def get_x_shape(self):
        return [100, 300]


class TestMeshgridOp3(unittest.TestCase):
    def test_api(self):
81 82
        x = paddle.static.data(shape=[100], dtype='int32', name='x')
        y = paddle.static.data(shape=[200], dtype='int32', name='y')
S
suytingwan 已提交
83

84 85 86 87 88 89 90 91 92
        input_1 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_2 = np.random.randint(
            0,
93
            100,
94 95 96 97
            [
                200,
            ],
        ).astype('int32')
S
suytingwan 已提交
98 99 100 101 102 103 104

        out_1 = np.reshape(input_1, [100, 1])
        out_1 = np.broadcast_to(out_1, [100, 200])
        out_2 = np.reshape(input_2, [1, 200])
        out_2 = np.broadcast_to(out_2, [100, 200])

        exe = fluid.Executor(place=fluid.CPUPlace())
105
        grid_x, grid_y = paddle.tensor.meshgrid(x, y)
106 107 108 109 110
        res_1, res_2 = exe.run(
            fluid.default_main_program(),
            feed={'x': input_1, 'y': input_2},
            fetch_list=[grid_x, grid_y],
        )
S
suytingwan 已提交
111 112 113 114 115
        assert np.array_equal(res_1, out_1)
        assert np.array_equal(res_2, out_2)


class TestMeshgridOp4(unittest.TestCase):
116
    def test_list_input(self):
117 118
        x = paddle.static.data(shape=[100], dtype='int32', name='x')
        y = paddle.static.data(shape=[200], dtype='int32', name='y')
S
suytingwan 已提交
119

120 121 122 123 124 125 126 127 128
        input_1 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_2 = np.random.randint(
            0,
129
            100,
130 131 132 133
            [
                200,
            ],
        ).astype('int32')
S
suytingwan 已提交
134

135 136 137 138 139 140 141
        out_1 = np.reshape(input_1, [100, 1])
        out_1 = np.broadcast_to(out_1, [100, 200])
        out_2 = np.reshape(input_2, [1, 200])
        out_2 = np.broadcast_to(out_2, [100, 200])

        exe = fluid.Executor(place=fluid.CPUPlace())
        grid_x, grid_y = paddle.tensor.meshgrid([x, y])
142 143 144 145 146
        res_1, res_2 = exe.run(
            fluid.default_main_program(),
            feed={'x': input_1, 'y': input_2},
            fetch_list=[grid_x, grid_y],
        )
147 148 149

        assert np.array_equal(res_1, out_1)
        assert np.array_equal(res_2, out_2)
S
suytingwan 已提交
150 151 152


class TestMeshgridOp5(unittest.TestCase):
153
    def test_tuple_input(self):
154 155
        x = paddle.static.data(shape=[100], dtype='int32', name='x')
        y = paddle.static.data(shape=[200], dtype='int32', name='y')
156

157 158 159 160 161 162 163 164 165
        input_1 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_2 = np.random.randint(
            0,
166
            100,
167 168 169 170
            [
                200,
            ],
        ).astype('int32')
171 172 173 174 175 176 177 178

        out_1 = np.reshape(input_1, [100, 1])
        out_1 = np.broadcast_to(out_1, [100, 200])
        out_2 = np.reshape(input_2, [1, 200])
        out_2 = np.broadcast_to(out_2, [100, 200])

        exe = fluid.Executor(place=fluid.CPUPlace())
        grid_x, grid_y = paddle.tensor.meshgrid((x, y))
179 180 181 182 183
        res_1, res_2 = exe.run(
            fluid.default_main_program(),
            feed={'x': input_1, 'y': input_2},
            fetch_list=[grid_x, grid_y],
        )
184 185 186 187 188 189

        assert np.array_equal(res_1, out_1)
        assert np.array_equal(res_2, out_2)


class TestMeshgridOp6(unittest.TestCase):
S
suytingwan 已提交
190
    def test_api_with_dygraph(self):
191 192 193 194 195 196 197 198 199
        input_3 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_4 = np.random.randint(
            0,
200
            100,
201 202 203 204
            [
                200,
            ],
        ).astype('int32')
S
suytingwan 已提交
205

206 207 208 209 210 211 212 213 214 215 216
        with fluid.dygraph.guard():
            tensor_3 = fluid.dygraph.to_variable(input_3)
            tensor_4 = fluid.dygraph.to_variable(input_4)
            res_3, res_4 = paddle.tensor.meshgrid(tensor_3, tensor_4)

            assert np.array_equal(res_3.shape, [100, 200])
            assert np.array_equal(res_4.shape, [100, 200])


class TestMeshgridOp7(unittest.TestCase):
    def test_api_with_dygraph_list_input(self):
217 218 219 220 221 222 223 224 225
        input_3 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_4 = np.random.randint(
            0,
226
            100,
227 228 229 230
            [
                200,
            ],
        ).astype('int32')
231

S
suytingwan 已提交
232 233 234 235 236 237 238 239 240
        with fluid.dygraph.guard():
            tensor_3 = fluid.dygraph.to_variable(input_3)
            tensor_4 = fluid.dygraph.to_variable(input_4)
            res_3, res_4 = paddle.tensor.meshgrid([tensor_3, tensor_4])

            assert np.array_equal(res_3.shape, [100, 200])
            assert np.array_equal(res_4.shape, [100, 200])


Z
zhangchunle 已提交
241
class TestMeshgridOp8(unittest.TestCase):
242
    def test_api_with_dygraph_tuple_input(self):
243 244 245 246 247 248 249 250 251
        input_3 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_4 = np.random.randint(
            0,
252
            100,
253 254 255 256
            [
                200,
            ],
        ).astype('int32')
257 258 259 260 261 262 263 264 265

        with fluid.dygraph.guard():
            tensor_3 = fluid.dygraph.to_variable(input_3)
            tensor_4 = fluid.dygraph.to_variable(input_4)
            res_3, res_4 = paddle.tensor.meshgrid((tensor_3, tensor_4))

            assert np.array_equal(res_3.shape, [100, 200])
            assert np.array_equal(res_4.shape, [100, 200])

Y
YuanRisheng 已提交
266

267 268 269 270 271
class TestMeshGrid_ZeroDim(TestMeshgridOp):
    def init_test_data(self):
        self.shape = self.get_x_shape()
        ins = []
        outs = []
272
        ins.append(np.random.random([]).astype(self.dtype))
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
        ins.append(np.random.random([2]).astype(self.dtype))
        ins.append(np.random.random([3]).astype(self.dtype))
        for i in range(len(self.shape)):
            out_reshape = [1] * len(self.shape)
            out_reshape[i] = self.shape[i]
            out_temp = np.reshape(ins[i], out_reshape)
            outs.append(np.broadcast_to(out_temp, self.shape))
        return ins, outs

    def get_x_shape(self):
        return [1, 2, 3]

    def if_enable_cinn(self):
        self.enable_cinn = False


Y
YuanRisheng 已提交
289
class TestMeshgridEager(unittest.TestCase):
290
    def test_dygraph_api(self):
291 292 293 294 295 296 297 298 299
        input_1 = np.random.randint(
            0,
            100,
            [
                100,
            ],
        ).astype('int32')
        input_2 = np.random.randint(
            0,
300
            100,
301 302 303 304
            [
                200,
            ],
        ).astype('int32')
Y
YuanRisheng 已提交
305 306 307 308 309 310 311 312 313

        with fluid.dygraph.guard():
            tensor_1 = fluid.dygraph.to_variable(input_1)
            tensor_2 = fluid.dygraph.to_variable(input_2)
            tensor_1.stop_gradient = False
            tensor_2.stop_gradient = False
            res_1, res_2 = paddle.tensor.meshgrid((tensor_1, tensor_2))
            sum = paddle.add_n([res_1, res_2])
            sum.backward()
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
            tensor_eager_1 = fluid.dygraph.to_variable(input_1)
            tensor_eager_2 = fluid.dygraph.to_variable(input_2)
            tensor_eager_1.stop_gradient = False
            tensor_eager_2.stop_gradient = False
            res_eager_1, res_eager_2 = paddle.tensor.meshgrid(
                (tensor_eager_1, tensor_eager_2)
            )
            sum_eager = paddle.add_n([res_eager_1, res_eager_2])
            sum_eager.backward()
            self.assertEqual(
                (tensor_1.grad.numpy() == tensor_eager_1.grad.numpy()).all(),
                True,
            )
            self.assertEqual(
                (tensor_2.grad.numpy() == tensor_eager_2.grad.numpy()).all(),
                True,
            )
Y
YuanRisheng 已提交
331

332

S
suytingwan 已提交
333
if __name__ == '__main__':
H
hong 已提交
334
    paddle.enable_static()
S
suytingwan 已提交
335
    unittest.main()