test_dist_op.py 5.6 KB
Newer Older
Z
Zhang Ting 已提交
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

Z
Zhang Ting 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest
19

Z
Zhang Ting 已提交
20 21 22 23
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core

P
pangyoki 已提交
24 25
paddle.enable_static()

Z
Zhang Ting 已提交
26 27

def dist(x, y, p):
28
    if p == 0.0:
Z
Zhang Ting 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41
        out = np.count_nonzero(x - y)
    elif p == float("inf"):
        out = np.max(np.abs(x - y))
    elif p == float("-inf"):
        out = np.min(np.abs(x - y))
    else:
        out = np.power(np.sum(np.power(np.abs(x - y), p)), 1.0 / p)
    return np.array(out).astype(x.dtype)


class TestDistOp(OpTest):
    def setUp(self):
        self.op_type = 'dist'
H
hong 已提交
42
        self.python_api = paddle.dist
Z
Zhang Ting 已提交
43 44
        self.attrs = {}
        self.init_case()
45
        self.init_data_type()
Z
Zhang Ting 已提交
46
        self.inputs = {
47
            "X": np.random.random(self.x_shape).astype(self.data_type),
48
            "Y": np.random.random(self.y_shape).astype(self.data_type),
Z
Zhang Ting 已提交
49 50 51 52 53 54 55 56 57
        }

        self.attrs["p"] = self.p
        self.outputs = {
            "Out": dist(self.inputs["X"], self.inputs["Y"], self.attrs["p"])
        }
        self.gradient = self.calc_gradient()

    def init_case(self):
58 59 60
        self.x_shape = 120
        self.y_shape = 120
        self.p = 0.0
Z
Zhang Ting 已提交
61

62
    def init_data_type(self):
63 64 65
        self.data_type = (
            np.float32 if core.is_compiled_with_rocm() else np.float64
        )
66

Z
Zhang Ting 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79
    def calc_gradient(self):
        x = self.inputs["X"]
        y = self.inputs["Y"]
        p = self.attrs["p"]
        if p == 0:
            grad = np.zeros(x.shape)
        elif p in [float("inf"), float("-inf")]:
            norm = dist(x, y, p)
            x_minux_y_abs = np.abs(x - y)
            grad = np.sign(x - y)
            grad[x_minux_y_abs != norm] = 0
        else:
            norm = dist(x, y, p)
80 81 82 83 84
            grad = (
                np.power(norm, 1 - p)
                * np.power(np.abs(x - y), p - 1)
                * np.sign(x - y)
            )
Z
Zhang Ting 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

        def get_reduce_dims(x, y):
            x_reduce_dims = []
            y_reduce_dims = []

            if x.ndim >= y.ndim:
                y_reshape = tuple([1] * (x.ndim - y.ndim) + list(y.shape))
                y = y.reshape(y_reshape)
            else:
                x_reshape = tuple([1] * (y.ndim - x.ndim) + list(x.shape))
                x = x.reshape(x_reshape)
            for i in range(x.ndim):
                if x.shape[i] > y.shape[i]:
                    y_reduce_dims.append(i)
                elif x.shape[i] < y.shape[i]:
                    x_reduce_dims.append(i)
            return x_reduce_dims, y_reduce_dims

        x_reduce_dims, y_reduce_dims = get_reduce_dims(x, y)
        if len(x_reduce_dims) != 0:
            x_grad = np.sum(grad, tuple(x_reduce_dims)).reshape(x.shape)
        else:
            x_grad = grad
        if len(y_reduce_dims) != 0:
            y_grad = -np.sum(grad, tuple(y_reduce_dims)).reshape(y.shape)
        else:
            y_grad = -grad

        return x_grad, y_grad

    def test_check_output(self):
W
wanghuancoder 已提交
116
        self.check_output()
Z
Zhang Ting 已提交
117 118

    def test_check_grad(self):
119 120 121 122 123
        self.check_grad(
            ["X", "Y"],
            "Out",
            user_defined_grads=self.gradient,
        )
Z
Zhang Ting 已提交
124 125 126 127 128 129


class TestDistOpCase1(TestDistOp):
    def init_case(self):
        self.x_shape = (3, 5, 5, 6)
        self.y_shape = (5, 5, 6)
130
        self.p = 1.0
Z
Zhang Ting 已提交
131 132 133 134 135 136


class TestDistOpCase2(TestDistOp):
    def init_case(self):
        self.x_shape = (10, 10)
        self.y_shape = (4, 10, 10)
137
        self.p = 2.0
Z
Zhang Ting 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161


class TestDistOpCase3(TestDistOp):
    def init_case(self):
        self.x_shape = (15, 10)
        self.y_shape = (15, 10)
        self.p = float("inf")


class TestDistOpCase4(TestDistOp):
    def init_case(self):
        self.x_shape = (2, 3, 4, 5, 8)
        self.y_shape = (3, 1, 5, 8)
        self.p = float("-inf")


class TestDistOpCase5(TestDistOp):
    def init_case(self):
        self.x_shape = (4, 1, 4, 8)
        self.y_shape = (2, 2, 1, 4, 4, 8)
        self.p = 1.5


class TestDistAPI(unittest.TestCase):
162
    def init_data_type(self):
163 164 165
        self.data_type = (
            'float32' if core.is_compiled_with_rocm() else 'float64'
        )
166

Z
Zhang Ting 已提交
167
    def test_api(self):
168
        self.init_data_type()
Z
Zhang Ting 已提交
169 170 171
        main_program = fluid.Program()
        startup_program = fluid.Program()
        with fluid.program_guard(main_program, startup_program):
172 173
            x = fluid.data(name='x', shape=[2, 3, 4, 5], dtype=self.data_type)
            y = fluid.data(name='y', shape=[3, 1, 5], dtype=self.data_type)
Z
Zhang Ting 已提交
174
            p = 2
175 176
            x_i = np.random.random((2, 3, 4, 5)).astype(self.data_type)
            y_i = np.random.random((3, 1, 5)).astype(self.data_type)
Z
Zhang Ting 已提交
177
            result = paddle.dist(x, y, p)
178 179 180 181 182
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
Z
Zhang Ting 已提交
183
            exe = fluid.Executor(place)
184 185 186 187 188
            out = exe.run(
                fluid.default_main_program(),
                feed={'x': x_i, 'y': y_i},
                fetch_list=[result],
            )
189
            np.testing.assert_allclose(dist(x_i, y_i, p), out[0], rtol=1e-05)
Z
Zhang Ting 已提交
190 191 192


if __name__ == '__main__':
H
hong 已提交
193
    paddle.enable_static()
Z
Zhang Ting 已提交
194
    unittest.main()