test_cholesky_op.py 5.7 KB
Newer Older
G
Guo Sheng 已提交
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

G
Guo Sheng 已提交
17
import numpy as np
18
from decorator_helper import prog_scope
姜永久 已提交
19
from eager_op_test import OpTest, skip_check_grad_ci
20 21
from gradient_checker import grad_check

G
Guo Sheng 已提交
22
import paddle
23 24
from paddle import fluid
from paddle.fluid import core
G
Guo Sheng 已提交
25 26 27


@skip_check_grad_ci(
28
    reason="The input of cholesky_op should always be symmetric positive-definite. "
G
Guo Sheng 已提交
29 30 31 32 33
    "However, OpTest calculates the numeric gradient of each element in input "
    "via small finite difference, which makes the input no longer symmetric "
    "positive-definite thus can not compute the Cholesky decomposition. "
    "While we can use the gradient_checker.grad_check to perform gradient "
    "check of cholesky_op, since it supports check gradient with a program "
34 35
    "and we can construct symmetric positive-definite matrices in the program"
)
G
Guo Sheng 已提交
36 37 38
class TestCholeskyOp(OpTest):
    def setUp(self):
        self.op_type = "cholesky"
姜永久 已提交
39
        self.python_api = paddle.cholesky
G
Guo Sheng 已提交
40 41 42 43
        self._input_shape = (2, 32, 32)
        self._upper = True
        self.init_config()
        self.trans_dims = list(range(len(self._input_shape) - 2)) + [
44
            len(self._input_shape) - 1,
45
            len(self._input_shape) - 2,
G
Guo Sheng 已提交
46 47 48
        ]
        self.root_data = np.random.random(self._input_shape).astype("float64")
        # construct symmetric positive-definite matrice
49 50 51 52
        input_data = (
            np.matmul(self.root_data, self.root_data.transpose(self.trans_dims))
            + 1e-05
        )
G
Guo Sheng 已提交
53 54 55 56 57 58 59 60 61 62 63 64
        output_data = np.linalg.cholesky(input_data).astype("float64")
        if self._upper:
            output_data = output_data.transpose(self.trans_dims)
        self.inputs = {"X": input_data}
        self.attrs = {"upper": self._upper}
        self.outputs = {"Out": output_data}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        places = [fluid.CPUPlace()]
F
furnace 已提交
65
        if core.is_compiled_with_cuda() and (not core.is_compiled_with_rocm()):
G
Guo Sheng 已提交
66 67 68 69 70 71 72 73 74 75
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)

    @prog_scope()
    def func(self, place):
        # use small size since Jacobian gradients is time consuming
        root_data = self.root_data[..., :3, :3]
        prog = fluid.Program()
        with fluid.program_guard(prog):
76
            root = paddle.create_parameter(
77 78
                dtype=root_data.dtype, shape=root_data.shape
            )
79
            root_t = paddle.transpose(root, self.trans_dims)
K
kangguangli 已提交
80
            x = paddle.matmul(x=root, y=root_t) + 1e-05
G
Guo Sheng 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94
            out = paddle.cholesky(x, upper=self.attrs["upper"])
            grad_check(root, out, x_init=root_data, place=place)

    def init_config(self):
        self._upper = True


class TestCholeskyOpLower(TestCholeskyOp):
    def init_config(self):
        self._upper = False


class TestCholeskyOp2D(TestCholeskyOp):
    def init_config(self):
G
Guo Sheng 已提交
95
        self._input_shape = (32, 32)
G
Guo Sheng 已提交
96 97


98 99
class TestDygraph(unittest.TestCase):
    def test_dygraph(self):
F
furnace 已提交
100 101 102 103
        if core.is_compiled_with_rocm():
            paddle.disable_static(place=fluid.CPUPlace())
        else:
            paddle.disable_static()
104 105 106
        a = np.random.rand(3, 3)
        a_t = np.transpose(a, [1, 0])
        x_data = np.matmul(a, a_t) + 1e-03
107
        x = paddle.to_tensor([x_data])
108 109 110
        out = paddle.cholesky(x, upper=False)


111 112 113
class TestCholeskySingularAPI(unittest.TestCase):
    def setUp(self):
        self.places = [fluid.CPUPlace()]
F
furnace 已提交
114
        if core.is_compiled_with_cuda() and (not core.is_compiled_with_rocm()):
115 116 117 118
            self.places.append(fluid.CUDAPlace(0))

    def check_static_result(self, place, with_out=False):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
119 120 121
            input = paddle.static.data(
                name="input", shape=[4, 4], dtype="float64"
            )
122 123 124 125 126 127
            result = paddle.cholesky(input)

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

            exe = fluid.Executor(place)
            try:
128 129 130 131 132
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": input_np},
                    fetch_list=[result],
                )
133 134 135
            except RuntimeError as ex:
                print("The mat is singular")
            except ValueError as ex:
136 137 138 139 140 141 142 143 144
                print("The mat is singular")

    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):
145 146 147 148 149 150
                input_np = np.array(
                    [
                        [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                        [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
                    ]
                ).astype("float64")
151 152 153
                input = fluid.dygraph.to_variable(input_np)
                try:
                    result = paddle.cholesky(input)
154 155 156
                except RuntimeError as ex:
                    print("The mat is singular")
                except ValueError as ex:
157 158 159
                    print("The mat is singular")


G
Guo Sheng 已提交
160
if __name__ == "__main__":
161
    paddle.enable_static()
G
Guo Sheng 已提交
162
    unittest.main()