test_meshgrid_op.py 8.8 KB
Newer Older
S
suytingwan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   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.

from __future__ import print_function

import unittest
import numpy as np
from op_test import OpTest, skip_check_grad_ci
import paddle.fluid as fluid
import paddle
from paddle.fluid import compiler, Program, program_guard, core
Y
YuanRisheng 已提交
23
from paddle.fluid.framework import _test_eager_guard
S
suytingwan 已提交
24 25 26


class TestMeshgridOp(OpTest):
27

S
suytingwan 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    def setUp(self):
        self.op_type = "meshgrid"
        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))]
        }

    def get_dtype(self):
        return "float64"

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['x0'], ['out0'])
        self.check_grad(['x1'], ['out1'])

    def init_test_data(self):
        self.shape = self.get_x_shape()
        ins = []
        outs = []
        for i in range(len(self.shape)):
            ins.append(np.random.random((self.shape[i], )).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 [100, 200]


class TestMeshgridOp2(TestMeshgridOp):
66

S
suytingwan 已提交
67 68 69 70 71
    def get_x_shape(self):
        return [100, 300]


class TestMeshgridOp3(unittest.TestCase):
72

S
suytingwan 已提交
73 74 75 76
    def test_api(self):
        x = fluid.data(shape=[100], dtype='int32', name='x')
        y = fluid.data(shape=[200], dtype='int32', name='y')

77 78 79 80 81 82
        input_1 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_2 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
S
suytingwan 已提交
83 84 85 86 87 88 89

        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())
90
        grid_x, grid_y = paddle.tensor.meshgrid(x, y)
S
suytingwan 已提交
91
        res_1, res_2 = exe.run(fluid.default_main_program(),
92 93 94 95
                               feed={
                                   'x': input_1,
                                   'y': input_2
                               },
S
suytingwan 已提交
96 97 98 99 100 101
                               fetch_list=[grid_x, grid_y])
        assert np.array_equal(res_1, out_1)
        assert np.array_equal(res_2, out_2)


class TestMeshgridOp4(unittest.TestCase):
102

103 104 105
    def test_list_input(self):
        x = fluid.data(shape=[100], dtype='int32', name='x')
        y = fluid.data(shape=[200], dtype='int32', name='y')
S
suytingwan 已提交
106

107 108 109 110 111 112
        input_1 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_2 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
S
suytingwan 已提交
113

114 115 116 117 118 119 120 121
        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])
        res_1, res_2 = exe.run(fluid.default_main_program(),
122 123 124 125
                               feed={
                                   'x': input_1,
                                   'y': input_2
                               },
126 127 128 129
                               fetch_list=[grid_x, grid_y])

        assert np.array_equal(res_1, out_1)
        assert np.array_equal(res_2, out_2)
S
suytingwan 已提交
130 131 132


class TestMeshgridOp5(unittest.TestCase):
133

134 135 136 137
    def test_tuple_input(self):
        x = fluid.data(shape=[100], dtype='int32', name='x')
        y = fluid.data(shape=[200], dtype='int32', name='y')

138 139 140 141 142 143
        input_1 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_2 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
144 145 146 147 148 149 150 151 152

        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))
        res_1, res_2 = exe.run(fluid.default_main_program(),
153 154 155 156
                               feed={
                                   'x': input_1,
                                   'y': input_2
                               },
157 158 159 160 161 162 163
                               fetch_list=[grid_x, grid_y])

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


class TestMeshgridOp6(unittest.TestCase):
164

S
suytingwan 已提交
165
    def test_api_with_dygraph(self):
166 167 168 169 170 171
        input_3 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_4 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
S
suytingwan 已提交
172

173 174 175 176 177 178 179 180
        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 已提交
181 182 183 184
    def test_api_eager_dygraph(self):
        with _test_eager_guard():
            self.test_api_with_dygraph()

185 186

class TestMeshgridOp7(unittest.TestCase):
187

188
    def test_api_with_dygraph_list_input(self):
189 190 191 192 193 194
        input_3 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_4 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
195

S
suytingwan 已提交
196 197 198 199 200 201 202 203
        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 已提交
204 205 206 207
    def test_api_eager_dygraph(self):
        with _test_eager_guard():
            self.test_api_with_dygraph_list_input()

S
suytingwan 已提交
208

Z
zhangchunle 已提交
209
class TestMeshgridOp8(unittest.TestCase):
210

211
    def test_api_with_dygraph_tuple_input(self):
212 213 214 215 216 217
        input_3 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_4 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
218 219 220 221 222 223 224 225 226

        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 已提交
227 228 229 230 231 232
    def test_api_eager_dygraph(self):
        with _test_eager_guard():
            self.test_api_with_dygraph_tuple_input()


class TestMeshgridEager(unittest.TestCase):
233

Y
YuanRisheng 已提交
234
    def test_dygraph_final_state_api(self):
235 236 237 238 239 240
        input_1 = np.random.randint(0, 100, [
            100,
        ]).astype('int32')
        input_2 = np.random.randint(0, 100, [
            200,
        ]).astype('int32')
Y
YuanRisheng 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

        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()
            with _test_eager_guard():
                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)

266

S
suytingwan 已提交
267
if __name__ == '__main__':
H
hong 已提交
268
    paddle.enable_static()
S
suytingwan 已提交
269
    unittest.main()