test_pairwise_distance.py 17.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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 paddle
import paddle.fluid as fluid
import numpy as np
import unittest


21 22 23 24 25 26 27
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
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
def call_pairwise_distance_layer(x, y, p=2., epsilon=1e-6, keepdim='False'):
    pairwise_distance = paddle.nn.PairwiseDistance(p=p,
                                                   epsilon=epsilon,
                                                   keepdim=keepdim)
    distance = pairwise_distance(x=x, y=y)
    return distance


def call_pairwise_distance_functional(x,
                                      y,
                                      p=2.,
                                      epsilon=1e-6,
                                      keepdim='False'):
    distance = paddle.nn.functional.pairwise_distance(x=x,
                                                      y=y,
                                                      p=p,
                                                      epsilon=epsilon,
                                                      keepdim=keepdim)
    return distance


def test_static(place,
                x_np,
                y_np,
                p=2.0,
                epsilon=1e-6,
                keepdim=False,
                functional=False):
58 59
    prog = paddle.static.Program()
    startup_prog = paddle.static.Program()
60 61
    place = fluid.CUDAPlace(
        0) if paddle.fluid.core.is_compiled_with_cuda() else fluid.CPUPlace()
62
    paddle.enable_static()
63
    with paddle.static.program_guard(prog, startup_prog):
64 65
        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)
66 67 68 69 70

        if functional:
            distance = call_pairwise_distance_functional(x=x,
                                                         y=y,
                                                         p=p,
71 72
                                                         epsilon=epsilon,
                                                         keepdim=keepdim)
73 74 75 76 77 78
        else:
            distance = call_pairwise_distance_layer(x=x,
                                                    y=y,
                                                    p=p,
                                                    epsilon=epsilon,
                                                    keepdim=keepdim)
79 80
        exe = paddle.static.Executor(place)
        static_ret = exe.run(prog,
81 82 83 84
                             feed={
                                 'x': x_np,
                                 'y': y_np
                             },
85 86
                             fetch_list=[distance])
        static_ret = static_ret[0]
87
    paddle.disable_static()
88 89 90
    return static_ret


91 92 93 94 95 96 97
def test_dygraph(place,
                 x_np,
                 y_np,
                 p=2.0,
                 epsilon=1e-6,
                 keepdim=False,
                 functional=False):
98 99
    x = paddle.to_tensor(x_np)
    y = paddle.to_tensor(y_np)
100 101 102 103 104 105 106 107 108 109 110 111 112
    if functional:
        dy_distance = call_pairwise_distance_functional(x=x,
                                                        y=y,
                                                        p=p,
                                                        epsilon=epsilon,
                                                        keepdim=keepdim)
    else:
        dy_distance = call_pairwise_distance_layer(x=x,
                                                   y=y,
                                                   p=p,
                                                   epsilon=epsilon,
                                                   keepdim=keepdim)
    dygraph_ret = dy_distance.numpy()
113 114 115
    return dygraph_ret


116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
def test_legacy_dygraph(place,
                        x_np,
                        y_np,
                        p=2.0,
                        epsilon=1e-6,
                        keepdim=False,
                        functional=False):
    paddle.fluid.framework._enable_legacy_dygraph()
    x = paddle.to_tensor(x_np)
    y = paddle.to_tensor(y_np)
    if functional:
        legacy_distance = call_pairwise_distance_functional(x=x,
                                                            y=y,
                                                            p=p,
                                                            epsilon=epsilon,
                                                            keepdim=keepdim)
    else:
        legacy_distance = call_pairwise_distance_layer(x=x,
                                                       y=y,
                                                       p=p,
                                                       epsilon=epsilon,
                                                       keepdim=keepdim)
    legacy_ret = legacy_distance.numpy()
    paddle.fluid.framework._disable_legacy_dygraph()
    return legacy_ret


143
class TestPairwiseDistance(unittest.TestCase):
144

145
    def test_pairwise_distance(self):
146 147
        epsilon = 1e-6
        all_shape = [[5], [100, 100]]
148
        dtypes = ['float32', 'float64']
149 150 151 152
        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))
153
        keeps = [False, True]
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        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)

                            static_ret = test_static(place,
                                                     x_np,
                                                     y_np,
                                                     p,
                                                     epsilon=epsilon,
                                                     keepdim=keepdim)
                            dygraph_ret = test_dygraph(place,
                                                       x_np,
170
                                                       y_np,
171 172
                                                       p,
                                                       epsilon=epsilon,
173
                                                       keepdim=keepdim)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
                            legacy_ret = test_legacy_dygraph(place,
                                                             x_np,
                                                             y_np,
                                                             p,
                                                             epsilon=epsilon,
                                                             keepdim=keepdim)
                            excepted_value = np_pairwise_distance(
                                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)
                            self.assertEqual(legacy_ret.shape,
                                             excepted_value.shape)

190 191 192 193 194 195 196 197 198
                            np.testing.assert_allclose(static_ret,
                                                       excepted_value,
                                                       rtol=1e-05)
                            np.testing.assert_allclose(dygraph_ret,
                                                       excepted_value,
                                                       rtol=1e-05)
                            np.testing.assert_allclose(legacy_ret,
                                                       excepted_value,
                                                       rtol=1e-05)
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

                            static_functional_ret = test_static(place,
                                                                x_np,
                                                                y_np,
                                                                p,
                                                                epsilon=epsilon,
                                                                keepdim=keepdim)
                            dygraph_functional_ret = test_dygraph(
                                place,
                                x_np,
                                y_np,
                                p,
                                epsilon=epsilon,
                                keepdim=keepdim)
                            legacy_functional_ret = test_legacy_dygraph(
                                place,
                                x_np,
                                y_np,
                                p,
                                epsilon=epsilon,
                                keepdim=keepdim)
220

221 222 223 224 225 226
                            self.assertEqual(static_functional_ret.shape,
                                             excepted_value.shape)
                            self.assertEqual(dygraph_functional_ret.shape,
                                             excepted_value.shape)
                            self.assertEqual(legacy_functional_ret.shape,
                                             excepted_value.shape)
227

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

    def test_pairwise_distance_broadcast_1(self):
239 240
        shape_x = [100, 100]
        shape_y = [100, 1]
241
        epsilon = 1e-6
242
        keepdim = False
243
        place = paddle.CPUPlace()
244 245
        x_np = np.random.random(shape_x).astype('float32')
        y_np = np.random.random(shape_y).astype('float32')
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        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)
        legacy_ret = test_legacy_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)

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

270 271 272
        np.testing.assert_allclose(static_ret, excepted_value, rtol=1e-05)
        np.testing.assert_allclose(dygraph_ret, excepted_value, rtol=1e-05)
        np.testing.assert_allclose(legacy_ret, excepted_value, rtol=1e-05)
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

        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)
        legacy_functional_ret = test_legacy_dygraph(place=place,
                                                    x_np=x_np,
                                                    y_np=y_np,
                                                    epsilon=epsilon,
                                                    keepdim=keepdim,
                                                    functional=True)

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

297 298 299 300 301 302 303 304 305
        np.testing.assert_allclose(static_functional_ret,
                                   excepted_value,
                                   rtol=1e-05)
        np.testing.assert_allclose(dygraph_functional_ret,
                                   excepted_value,
                                   rtol=1e-05)
        np.testing.assert_allclose(legacy_functional_ret,
                                   excepted_value,
                                   rtol=1e-05)
306 307 308 309 310

    def test_pairwise_distance_broadcast_2(self):
        shape_x = [100, 100]
        shape_y = [100]
        epsilon = 1e-6
311
        keepdim = False
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
        place = paddle.CPUPlace()
        x_np = np.random.random(shape_x).astype('float32')
        y_np = np.random.random(shape_y).astype('float32')
        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)
        legacy_ret = test_legacy_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)

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

339 340 341
        np.testing.assert_allclose(static_ret, excepted_value, rtol=1e-05)
        np.testing.assert_allclose(dygraph_ret, excepted_value, rtol=1e-05)
        np.testing.assert_allclose(legacy_ret, excepted_value, rtol=1e-05)
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365

        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)
        legacy_functional_ret = test_legacy_dygraph(place=place,
                                                    x_np=x_np,
                                                    y_np=y_np,
                                                    epsilon=epsilon,
                                                    keepdim=keepdim,
                                                    functional=True)

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

366 367 368 369 370 371 372 373 374
        np.testing.assert_allclose(static_functional_ret,
                                   excepted_value,
                                   rtol=1e-05)
        np.testing.assert_allclose(dygraph_functional_ret,
                                   excepted_value,
                                   rtol=1e-05)
        np.testing.assert_allclose(legacy_functional_ret,
                                   excepted_value,
                                   rtol=1e-05)
375 376 377 378


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