test_pairwise_distance.py 10.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15 16 17 18
import unittest

import numpy as np

19 20 21 22
import paddle
import paddle.fluid as fluid


23 24 25 26 27 28 29
def np_pairwise_distance(x, y, p=2.0, epsilon=1e-6, keepdim=False):
    distance = np.linalg.norm(x - y + epsilon, ord=p, axis=-1, keepdims=keepdim)
    # Paddle currently has not supported for 0-d Tensors, so even if keep_dim is False,
    # and neither x nor y is batched, a Tensor of shape (1, ) is returned
    if distance.ndim == 0:
        distance = np.expand_dims(distance, axis=0)
    return distance
30 31


32 33 34 35
def call_pairwise_distance_layer(x, y, p=2.0, epsilon=1e-6, keepdim='False'):
    pairwise_distance = paddle.nn.PairwiseDistance(
        p=p, epsilon=epsilon, keepdim=keepdim
    )
36 37 38 39
    distance = pairwise_distance(x=x, y=y)
    return distance


40 41 42 43 44 45
def call_pairwise_distance_functional(
    x, y, p=2.0, epsilon=1e-6, keepdim='False'
):
    distance = paddle.nn.functional.pairwise_distance(
        x=x, y=y, p=p, epsilon=epsilon, keepdim=keepdim
    )
46 47 48
    return distance


49 50 51
def test_static(
    place, x_np, y_np, p=2.0, epsilon=1e-6, keepdim=False, functional=False
):
52 53
    prog = paddle.static.Program()
    startup_prog = paddle.static.Program()
54 55 56 57 58
    place = (
        fluid.CUDAPlace(0)
        if paddle.fluid.core.is_compiled_with_cuda()
        else fluid.CPUPlace()
    )
59
    paddle.enable_static()
60
    with paddle.static.program_guard(prog, startup_prog):
61 62
        x = paddle.fluid.data(name='x', shape=x_np.shape, dtype=x_np.dtype)
        y = paddle.fluid.data(name='y', shape=y_np.shape, dtype=x_np.dtype)
63 64

        if functional:
65 66 67
            distance = call_pairwise_distance_functional(
                x=x, y=y, p=p, epsilon=epsilon, keepdim=keepdim
            )
68
        else:
69 70 71
            distance = call_pairwise_distance_layer(
                x=x, y=y, p=p, epsilon=epsilon, keepdim=keepdim
            )
72
        exe = paddle.static.Executor(place)
73 74 75
        static_ret = exe.run(
            prog, feed={'x': x_np, 'y': y_np}, fetch_list=[distance]
        )
76
        static_ret = static_ret[0]
77
    paddle.disable_static()
78 79 80
    return static_ret


81 82 83
def test_dygraph(
    place, x_np, y_np, p=2.0, epsilon=1e-6, keepdim=False, functional=False
):
84 85
    x = paddle.to_tensor(x_np)
    y = paddle.to_tensor(y_np)
86
    if functional:
87 88 89
        dy_distance = call_pairwise_distance_functional(
            x=x, y=y, p=p, epsilon=epsilon, keepdim=keepdim
        )
90
    else:
91 92 93
        dy_distance = call_pairwise_distance_layer(
            x=x, y=y, p=p, epsilon=epsilon, keepdim=keepdim
        )
94
    dygraph_ret = dy_distance.numpy()
95 96 97 98 99
    return dygraph_ret


class TestPairwiseDistance(unittest.TestCase):
    def test_pairwise_distance(self):
100 101
        epsilon = 1e-6
        all_shape = [[5], [100, 100]]
102
        dtypes = ['float32', 'float64']
103 104 105 106
        p_list = [-1, 0, 1, 2, np.inf, -np.inf]
        places = [paddle.CPUPlace()]
        if paddle.device.is_compiled_with_cuda():
            places.append(paddle.CUDAPlace(0))
107
        keeps = [False, True]
108 109 110 111 112 113 114 115
        for place in places:
            for shape in all_shape:
                for dtype in dtypes:
                    for p in p_list:
                        for keepdim in keeps:
                            x_np = np.random.random(shape).astype(dtype)
                            y_np = np.random.random(shape).astype(dtype)

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
                            static_ret = test_static(
                                place,
                                x_np,
                                y_np,
                                p,
                                epsilon=epsilon,
                                keepdim=keepdim,
                            )
                            dygraph_ret = test_dygraph(
                                place,
                                x_np,
                                y_np,
                                p,
                                epsilon=epsilon,
                                keepdim=keepdim,
                            )
132
                            excepted_value = np_pairwise_distance(
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
                                x_np, y_np, p, epsilon=epsilon, keepdim=keepdim
                            )

                            self.assertEqual(
                                static_ret.shape, excepted_value.shape
                            )
                            self.assertEqual(
                                dygraph_ret.shape, excepted_value.shape
                            )

                            np.testing.assert_allclose(
                                static_ret, excepted_value, rtol=1e-05
                            )
                            np.testing.assert_allclose(
                                dygraph_ret, excepted_value, rtol=1e-05
                            )
                            static_functional_ret = test_static(
                                place,
                                x_np,
                                y_np,
                                p,
                                epsilon=epsilon,
                                keepdim=keepdim,
                            )
157 158 159 160 161 162
                            dygraph_functional_ret = test_dygraph(
                                place,
                                x_np,
                                y_np,
                                p,
                                epsilon=epsilon,
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
                                keepdim=keepdim,
                            )

                            self.assertEqual(
                                static_functional_ret.shape,
                                excepted_value.shape,
                            )
                            self.assertEqual(
                                dygraph_functional_ret.shape,
                                excepted_value.shape,
                            )

                            np.testing.assert_allclose(
                                static_functional_ret,
                                excepted_value,
                                rtol=1e-05,
                            )
                            np.testing.assert_allclose(
                                dygraph_functional_ret,
                                excepted_value,
                                rtol=1e-05,
                            )
185 186

    def test_pairwise_distance_broadcast_1(self):
187 188
        shape_x = [100, 100]
        shape_y = [100, 1]
189
        epsilon = 1e-6
190
        keepdim = False
191
        place = paddle.CPUPlace()
192 193
        x_np = np.random.random(shape_x).astype('float32')
        y_np = np.random.random(shape_y).astype('float32')
194 195 196 197 198 199 200 201 202
        static_ret = test_static(
            place=place, x_np=x_np, y_np=y_np, epsilon=epsilon, keepdim=keepdim
        )
        dygraph_ret = test_dygraph(
            place=place, x_np=x_np, y_np=y_np, epsilon=epsilon, keepdim=keepdim
        )
        excepted_value = np_pairwise_distance(
            x_np, y_np, epsilon=epsilon, keepdim=keepdim
        )
203 204 205 206

        self.assertEqual(static_ret.shape, excepted_value.shape)
        self.assertEqual(dygraph_ret.shape, excepted_value.shape)

207 208
        np.testing.assert_allclose(static_ret, excepted_value, rtol=1e-05)
        np.testing.assert_allclose(dygraph_ret, excepted_value, rtol=1e-05)
209

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        static_functional_ret = test_static(
            place=place,
            x_np=x_np,
            y_np=y_np,
            epsilon=epsilon,
            keepdim=keepdim,
            functional=True,
        )
        dygraph_functional_ret = test_dygraph(
            place=place,
            x_np=x_np,
            y_np=y_np,
            epsilon=epsilon,
            keepdim=keepdim,
            functional=True,
        )
226 227 228

        self.assertEqual(static_functional_ret.shape, excepted_value.shape)
        self.assertEqual(dygraph_functional_ret.shape, excepted_value.shape)
229

230 231 232 233 234 235
        np.testing.assert_allclose(
            static_functional_ret, excepted_value, rtol=1e-05
        )
        np.testing.assert_allclose(
            dygraph_functional_ret, excepted_value, rtol=1e-05
        )
236 237 238 239 240

    def test_pairwise_distance_broadcast_2(self):
        shape_x = [100, 100]
        shape_y = [100]
        epsilon = 1e-6
241
        keepdim = False
242 243 244
        place = paddle.CPUPlace()
        x_np = np.random.random(shape_x).astype('float32')
        y_np = np.random.random(shape_y).astype('float32')
245 246 247 248 249 250
        static_ret = test_static(
            place=place, x_np=x_np, y_np=y_np, epsilon=epsilon, keepdim=keepdim
        )
        dygraph_ret = test_dygraph(
            place=place, x_np=x_np, y_np=y_np, epsilon=epsilon, keepdim=keepdim
        )
W
Weilong Wu 已提交
251

252 253 254
        excepted_value = np_pairwise_distance(
            x_np, y_np, epsilon=epsilon, keepdim=keepdim
        )
255 256 257 258

        self.assertEqual(static_ret.shape, excepted_value.shape)
        self.assertEqual(dygraph_ret.shape, excepted_value.shape)

259 260
        np.testing.assert_allclose(static_ret, excepted_value, rtol=1e-05)
        np.testing.assert_allclose(dygraph_ret, excepted_value, rtol=1e-05)
261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        static_functional_ret = test_static(
            place=place,
            x_np=x_np,
            y_np=y_np,
            epsilon=epsilon,
            keepdim=keepdim,
            functional=True,
        )
        dygraph_functional_ret = test_dygraph(
            place=place,
            x_np=x_np,
            y_np=y_np,
            epsilon=epsilon,
            keepdim=keepdim,
            functional=True,
        )
278 279 280 281

        self.assertEqual(static_functional_ret.shape, excepted_value.shape)
        self.assertEqual(dygraph_functional_ret.shape, excepted_value.shape)

282 283 284 285 286 287
        np.testing.assert_allclose(
            static_functional_ret, excepted_value, rtol=1e-05
        )
        np.testing.assert_allclose(
            dygraph_functional_ret, excepted_value, rtol=1e-05
        )
288

289
    def test_pairwise_distance_fp16(self):
290 291 292 293 294 295 296
        shape = [100, 100]
        if not paddle.device.is_compiled_with_cuda():
            return
        place = paddle.CUDAPlace(0)
        x_np = np.random.random(shape).astype('float16')
        y_np = np.random.random(shape).astype('float16')
        static_ret = test_static(place, x_np, y_np)
297

298 299 300

if __name__ == "__main__":
    unittest.main()