test_matrix_power_op.py 10.7 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 23 24 25
# Copyright (c) 2021 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
import numpy as np
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle
from op_test import OpTest

paddle.enable_static()


class TestMatrixPowerOp(OpTest):
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 0

    def setUp(self):
        self.op_type = "matrix_power"
        self.config()

        np.random.seed(123)
        mat = np.random.random(self.matrix_shape).astype(self.dtype)
        powered_mat = np.linalg.matrix_power(mat, self.n)

        self.inputs = {"X": mat}
        self.outputs = {"Out": powered_mat}
        self.attrs = {"n": self.n}

    def test_check_output(self):
        self.check_output()

    def test_grad(self):
48 49 50 51
        self.check_grad(["X"],
                        "Out",
                        numeric_grad_delta=1e-5,
                        max_relative_error=1e-7)
52 53 54


class TestMatrixPowerOpN1(TestMatrixPowerOp):
55

56 57 58 59 60 61 62
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 1


class TestMatrixPowerOpN2(TestMatrixPowerOp):
63

64 65 66 67 68 69 70
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 2


class TestMatrixPowerOpN3(TestMatrixPowerOp):
71

72 73 74 75 76 77 78
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 3


class TestMatrixPowerOpN4(TestMatrixPowerOp):
79

80 81 82 83 84 85 86
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 4


class TestMatrixPowerOpN5(TestMatrixPowerOp):
87

88 89 90 91 92 93 94
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 5


class TestMatrixPowerOpN6(TestMatrixPowerOp):
95

96 97 98 99 100 101 102
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 6


class TestMatrixPowerOpN10(TestMatrixPowerOp):
103

104 105 106 107 108 109 110
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 10


class TestMatrixPowerOpNMinus(TestMatrixPowerOp):
111

112 113 114 115 116 117
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -1

    def test_grad(self):
118 119 120 121
        self.check_grad(["X"],
                        "Out",
                        numeric_grad_delta=1e-5,
                        max_relative_error=1e-6)
122 123 124


class TestMatrixPowerOpNMinus2(TestMatrixPowerOpNMinus):
125

126 127 128 129 130 131 132
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -2


class TestMatrixPowerOpNMinus3(TestMatrixPowerOpNMinus):
133

134 135 136 137 138 139 140
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -3


class TestMatrixPowerOpNMinus4(TestMatrixPowerOpNMinus):
141

142 143 144 145 146 147 148
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -4


class TestMatrixPowerOpNMinus5(TestMatrixPowerOpNMinus):
149

150 151 152 153 154 155 156
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -5


class TestMatrixPowerOpNMinus6(TestMatrixPowerOpNMinus):
157

158 159 160 161 162 163 164
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -6


class TestMatrixPowerOpNMinus10(TestMatrixPowerOp):
165

166 167 168 169 170 171
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = -10

    def test_grad(self):
172 173 174 175
        self.check_grad(["X"],
                        "Out",
                        numeric_grad_delta=1e-5,
                        max_relative_error=1e-6)
176 177 178


class TestMatrixPowerOpBatched1(TestMatrixPowerOp):
179

180 181 182 183 184 185 186
    def config(self):
        self.matrix_shape = [8, 4, 4]
        self.dtype = "float64"
        self.n = 5


class TestMatrixPowerOpBatched2(TestMatrixPowerOp):
187

188 189 190 191 192 193 194
    def config(self):
        self.matrix_shape = [2, 6, 4, 4]
        self.dtype = "float64"
        self.n = 4


class TestMatrixPowerOpBatched3(TestMatrixPowerOp):
195

196 197 198 199 200 201 202
    def config(self):
        self.matrix_shape = [2, 6, 4, 4]
        self.dtype = "float64"
        self.n = 0


class TestMatrixPowerOpBatchedLong(TestMatrixPowerOp):
203

204 205 206 207 208 209 210
    def config(self):
        self.matrix_shape = [1, 2, 3, 4, 4, 3, 3]
        self.dtype = "float64"
        self.n = 3


class TestMatrixPowerOpLarge1(TestMatrixPowerOp):
211

212 213 214 215 216 217 218
    def config(self):
        self.matrix_shape = [32, 32]
        self.dtype = "float64"
        self.n = 3


class TestMatrixPowerOpLarge2(TestMatrixPowerOp):
219

220 221 222 223 224 225 226
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float64"
        self.n = 32


class TestMatrixPowerOpFP32(TestMatrixPowerOp):
227

228 229 230 231 232 233 234 235 236 237
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float32"
        self.n = 2

    def test_grad(self):
        self.check_grad(["X"], "Out", max_relative_error=1e-2)


class TestMatrixPowerOpBatchedFP32(TestMatrixPowerOpFP32):
238

239 240 241 242 243 244 245
    def config(self):
        self.matrix_shape = [2, 8, 4, 4]
        self.dtype = "float32"
        self.n = 2


class TestMatrixPowerOpLarge1FP32(TestMatrixPowerOpFP32):
246

247 248 249 250 251 252 253
    def config(self):
        self.matrix_shape = [32, 32]
        self.dtype = "float32"
        self.n = 2


class TestMatrixPowerOpLarge2FP32(TestMatrixPowerOpFP32):
254

255 256 257 258 259 260 261
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float32"
        self.n = 32


class TestMatrixPowerOpFP32Minus(TestMatrixPowerOpFP32):
262

263 264 265 266 267 268 269
    def config(self):
        self.matrix_shape = [10, 10]
        self.dtype = "float32"
        self.n = -1


class TestMatrixPowerAPI(unittest.TestCase):
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    def setUp(self):
        np.random.seed(123)
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input_x = fluid.data(name="input_x", shape=[4, 4], dtype="float64")
            result = paddle.linalg.matrix_power(x=input_x, n=-2)
            input_np = np.random.random([4, 4]).astype("float64")
            result_np = np.linalg.matrix_power(input_np, -2)

            exe = fluid.Executor(place)
            fetches = exe.run(fluid.default_main_program(),
                              feed={"input_x": input_np},
                              fetch_list=[result])
288 289 290
            np.testing.assert_allclose(fetches[0],
                                       np.linalg.matrix_power(input_np, -2),
                                       rtol=1e-05)
291 292 293 294 295 296 297 298 299 300 301

    def test_static(self):
        for place in self.places:
            self.check_static_result(place=place)

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                input_np = np.random.random([4, 4]).astype("float64")
                input = paddle.to_tensor(input_np)
                result = paddle.linalg.matrix_power(input, -2)
302 303 304
                np.testing.assert_allclose(result.numpy(),
                                           np.linalg.matrix_power(input_np, -2),
                                           rtol=1e-05)
305 306 307


class TestMatrixPowerAPIError(unittest.TestCase):
308

309 310 311 312 313 314 315 316
    def test_errors(self):
        input_np = np.random.random([4, 4]).astype("float64")

        # input must be Variable.
        self.assertRaises(TypeError, paddle.linalg.matrix_power, input_np)

        # n must be int
        for n in [2.0, '2', -2.0]:
317 318 319
            input = fluid.data(name="input_float32",
                               shape=[4, 4],
                               dtype='float32')
320 321
            self.assertRaises(TypeError, paddle.linalg.matrix_power, input, n)

322
        # The data type of input must be float32 or float64.
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
        for dtype in ["bool", "int32", "int64", "float16"]:
            input = fluid.data(name="input_" + dtype, shape=[4, 4], dtype=dtype)
            self.assertRaises(TypeError, paddle.linalg.matrix_power, input, 2)

        # When out is set, the data type must be the same as input.
        input = fluid.data(name="input_1", shape=[4, 4], dtype="float32")
        out = fluid.data(name="output", shape=[4, 4], dtype="float64")
        self.assertRaises(TypeError, paddle.linalg.matrix_power, input, 2, out)

        # The number of dimensions of input must be >= 2.
        input = fluid.data(name="input_2", shape=[4], dtype="float32")
        self.assertRaises(ValueError, paddle.linalg.matrix_power, input, 2)

        # The inner-most 2 dimensions of input should be equal to each other
        input = fluid.data(name="input_3", shape=[4, 5], dtype="float32")
        self.assertRaises(ValueError, paddle.linalg.matrix_power, input, 2)


class TestMatrixPowerSingularAPI(unittest.TestCase):
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    def setUp(self):
        self.places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input = fluid.data(name="input", shape=[4, 4], dtype="float64")
            result = paddle.linalg.matrix_power(x=input, n=-2)

            input_np = np.zeros([4, 4]).astype("float64")

            exe = fluid.Executor(place)
            try:
                fetches = exe.run(fluid.default_main_program(),
                                  feed={"input": input_np},
                                  fetch_list=[result])
            except RuntimeError as ex:
                print("The mat is singular")
            except ValueError as ex:
                print("The mat is singular")

    def test_static(self):
        paddle.enable_static()
        for place in self.places:
            self.check_static_result(place=place)
        paddle.disable_static()

    def test_dygraph(self):
        for place in self.places:
            with fluid.dygraph.guard(place):
                input_np = np.ones([4, 4]).astype("float64")
                input = fluid.dygraph.to_variable(input_np)
                try:
                    result = paddle.linalg.matrix_power(input, -2)
                except RuntimeError as ex:
                    print("The mat is singular")
                except ValueError as ex:
                    print("The mat is singular")


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