test_pairwise_distance.py 16.8 KB
Newer Older
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 paddle
import paddle.fluid as fluid
import numpy as np
import unittest


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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
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):
60 61
    prog = paddle.static.Program()
    startup_prog = paddle.static.Program()
62 63
    place = fluid.CUDAPlace(
        0) if paddle.fluid.core.is_compiled_with_cuda() else fluid.CPUPlace()
64
    paddle.enable_static()
65
    with paddle.static.program_guard(prog, startup_prog):
66 67
        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)
68 69 70 71 72

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


93 94 95 96 97 98 99
def test_dygraph(place,
                 x_np,
                 y_np,
                 p=2.0,
                 epsilon=1e-6,
                 keepdim=False,
                 functional=False):
100 101
    x = paddle.to_tensor(x_np)
    y = paddle.to_tensor(y_np)
102 103 104 105 106 107 108 109 110 111 112 113 114
    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()
115 116 117
    return dygraph_ret


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 143 144
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


145
class TestPairwiseDistance(unittest.TestCase):
146

147
    def test_pairwise_distance(self):
148 149
        epsilon = 1e-6
        all_shape = [[5], [100, 100]]
150
        dtypes = ['float32', 'float64']
151 152 153 154
        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))
155
        keeps = [False, True]
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
        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,
172
                                                       y_np,
173 174
                                                       p,
                                                       epsilon=epsilon,
175
                                                       keepdim=keepdim)
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
                            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)

                            self.assertTrue(
                                np.allclose(static_ret, excepted_value))
                            self.assertTrue(
                                np.allclose(dygraph_ret, excepted_value))
                            self.assertTrue(
                                np.allclose(legacy_ret, excepted_value))

                            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)
219

220 221 222 223 224 225
                            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)
226

227 228 229 230 231 232 233 234 235 236 237
                            self.assertTrue(
                                np.allclose(static_functional_ret,
                                            excepted_value))
                            self.assertTrue(
                                np.allclose(dygraph_functional_ret,
                                            excepted_value))
                            self.assertTrue(
                                np.allclose(legacy_functional_ret,
                                            excepted_value))

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

269 270
        self.assertTrue(np.allclose(static_ret, excepted_value))
        self.assertTrue(np.allclose(dygraph_ret, excepted_value))
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        self.assertTrue(np.allclose(legacy_ret, excepted_value))

        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)
295

296 297 298 299 300 301 302 303
        self.assertTrue(np.allclose(static_functional_ret, excepted_value))
        self.assertTrue(np.allclose(dygraph_functional_ret, excepted_value))
        self.assertTrue(np.allclose(legacy_functional_ret, excepted_value))

    def test_pairwise_distance_broadcast_2(self):
        shape_x = [100, 100]
        shape_y = [100]
        epsilon = 1e-6
304
        keepdim = False
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        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)

332 333
        self.assertTrue(np.allclose(static_ret, excepted_value))
        self.assertTrue(np.allclose(dygraph_ret, excepted_value))
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        self.assertTrue(np.allclose(legacy_ret, excepted_value))

        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)

        self.assertTrue(np.allclose(static_functional_ret, excepted_value))
        self.assertTrue(np.allclose(dygraph_functional_ret, excepted_value))
        self.assertTrue(np.allclose(legacy_functional_ret, excepted_value))
362 363 364 365


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