test_cholesky_solve_op.py 9.5 KB
Newer Older
Z
zhiboniu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   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.w

from __future__ import print_function

import unittest
import numpy as np
import scipy
import scipy.linalg

import sys
23

Z
zhiboniu 已提交
24 25 26 27 28 29 30 31 32
sys.path.append("..")
import paddle
from op_test import OpTest
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard, core

paddle.enable_static()


33
#cholesky_solve implement 1
Z
zhiboniu 已提交
34 35 36 37 38 39 40 41 42 43
def cholesky_solution(X, B, upper=True):
    if upper:
        A = np.triu(X)
        L = A.T
        U = A
    else:
        A = np.tril(X)
        L = A
        U = A.T
    return scipy.linalg.solve_triangular(
44
        U, scipy.linalg.solve_triangular(L, B, lower=True))
Z
zhiboniu 已提交
45 46


47
#cholesky_solve implement 2
Z
zhiboniu 已提交
48 49 50
def scipy_cholesky_solution(X, B, upper=True):
    if upper:
        umat = np.triu(X)
51
        A = umat.T @ umat
Z
zhiboniu 已提交
52 53
    else:
        umat = np.tril(X)
54
        A = umat @ umat.T
Z
zhiboniu 已提交
55 56 57 58
    K = scipy.linalg.cho_factor(A)
    return scipy.linalg.cho_solve(K, B)


59 60
#broadcast function used by cholesky_solve
def broadcast_shape(matA, matB):
Z
zhiboniu 已提交
61 62
    shapeA = matA.shape
    shapeB = matB.shape
63
    Broadshape = []
Z
zhiboniu 已提交
64 65
    for idx in range(len(shapeA) - 2):
        if shapeA[idx] == shapeB[idx]:
66
            Broadshape.append(shapeA[idx])
Z
zhiboniu 已提交
67 68
            continue
        elif shapeA[idx] == 1 or shapeB[idx] == 1:
69
            Broadshape.append(max(shapeA[idx], shapeB[idx]))
Z
zhiboniu 已提交
70 71
        else:
            raise Exception(
72
                'shapeA and shapeB should be broadcasted, but got {} and {}'.
Z
zhiboniu 已提交
73
                format(shapeA, shapeB))
74 75
    bsA = Broadshape + list(shapeA[-2:])
    bsB = Broadshape + list(shapeB[-2:])
Z
zhiboniu 已提交
76 77 78
    return np.broadcast_to(matA, bsA), np.broadcast_to(matB, bsB)


79
#cholesky_solve implement in batch
Z
zhiboniu 已提交
80
def scipy_cholesky_solution_batch(bumat, bB, upper=True):
81
    bumat, bB = broadcast_shape(bumat, bB)
Z
zhiboniu 已提交
82 83 84 85 86 87 88 89 90
    ushape = bumat.shape
    bshape = bB.shape
    bumat = bumat.reshape((-1, ushape[-2], ushape[-1]))
    bB = bB.reshape((-1, bshape[-2], bshape[-1]))
    batch = 1
    for d in ushape[:-2]:
        batch *= d
    bx = []
    for b in range(batch):
91
        # x = scipy_cholesky_solution(bumat[b], bB[b], upper)   #large matrix result error
Z
zhiboniu 已提交
92 93 94 95 96
        x = cholesky_solution(bumat[b], bB[b], upper)
        bx.append(x)
    return np.array(bx).reshape(bshape)


97 98
# test condition: shape: 2D + 2D , upper=False
# based on OpTest class
Z
zhiboniu 已提交
99 100 101 102 103
class TestCholeskySolveOp(OpTest):
    """
    case 1
    """

104
    #test condition set
Z
zhiboniu 已提交
105 106 107 108
    def config(self):
        self.y_shape = [15, 15]
        self.x_shape = [15, 5]
        self.upper = False
109
        self.dtype = np.float64  #Here cholesky_solve Op only supports float64/float32 type, please check others if Op supports more types.
Z
zhiboniu 已提交
110

111
    #get scipy result
Z
zhiboniu 已提交
112 113
    def set_output(self):
        umat = self.inputs['Y']
114 115 116
        self.output = scipy_cholesky_solution_batch(umat,
                                                    self.inputs['X'],
                                                    upper=self.upper)
Z
zhiboniu 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

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

        if self.upper:
            umat = np.triu(np.random.random(self.y_shape).astype(self.dtype))
        else:
            umat = np.tril(np.random.random(self.y_shape).astype(self.dtype))

        self.inputs = {
            'X': np.random.random(self.x_shape).astype(self.dtype),
            'Y': umat
        }
        self.attrs = {'upper': self.upper}
        self.set_output()
        self.outputs = {'Out': self.output}

135
    #check Op forward result
Z
zhiboniu 已提交
136 137 138
    def test_check_output(self):
        self.check_output()

139
    #check Op grad
Z
zhiboniu 已提交
140 141 142 143
    def test_check_grad_normal(self):
        self.check_grad(['Y'], 'Out', max_relative_error=0.01)


144
# test condition:  3D(broadcast) + 3D, upper=True
Z
zhiboniu 已提交
145 146 147 148 149 150 151 152 153 154 155 156
class TestCholeskySolveOp3(TestCholeskySolveOp):
    """
    case 3
    """

    def config(self):
        self.y_shape = [1, 10, 10]
        self.x_shape = [2, 10, 5]
        self.upper = True
        self.dtype = np.float64


157
#API function test
Z
zhiboniu 已提交
158
class TestCholeskySolveAPI(unittest.TestCase):
159

Z
zhiboniu 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    def setUp(self):
        np.random.seed(2021)
        self.place = [paddle.CPUPlace()]
        self.dtype = "float64"
        self.upper = True
        if core.is_compiled_with_cuda():
            self.place.append(paddle.CUDAPlace(0))

    def check_static_result(self, place):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            x = fluid.data(name="x", shape=[10, 2], dtype=self.dtype)
            y = fluid.data(name="y", shape=[10, 10], dtype=self.dtype)
            z = paddle.linalg.cholesky_solve(x, y, upper=self.upper)

            x_np = np.random.random([10, 2]).astype(self.dtype)
            y_np = np.random.random([10, 10]).astype(self.dtype)
            if self.upper:
                umat = np.triu(y_np)
            else:
                umat = np.tril(y_np)
            z_np = cholesky_solution(umat, x_np, upper=self.upper)
            z2_np = scipy_cholesky_solution(umat, x_np, upper=self.upper)

            exe = fluid.Executor(place)
            fetches = exe.run(fluid.default_main_program(),
186 187 188 189
                              feed={
                                  "x": x_np,
                                  "y": umat
                              },
Z
zhiboniu 已提交
190
                              fetch_list=[z])
191
            np.testing.assert_allclose(fetches[0], z_np, rtol=1e-05)
Z
zhiboniu 已提交
192

193
    #test in static mode
Z
zhiboniu 已提交
194 195 196 197
    def test_static(self):
        for place in self.place:
            self.check_static_result(place=place)

198
    #test in dynamic mode
Z
zhiboniu 已提交
199
    def test_dygraph(self):
200

Z
zhiboniu 已提交
201 202 203 204 205 206 207 208 209 210
        def run(place):
            paddle.disable_static(place)
            x_np = np.random.random([20, 2]).astype(self.dtype)
            y_np = np.random.random([20, 20]).astype(self.dtype)
            z_np = scipy_cholesky_solution(y_np, x_np, upper=self.upper)

            x = paddle.to_tensor(x_np)
            y = paddle.to_tensor(y_np)
            z = paddle.linalg.cholesky_solve(x, y, upper=self.upper)

211
            np.testing.assert_allclose(z_np, z.numpy(), rtol=1e-05)
Z
zhiboniu 已提交
212 213 214 215 216 217
            self.assertEqual(z_np.shape, z.numpy().shape)
            paddle.enable_static()

        for idx, place in enumerate(self.place):
            run(place)

218 219
    #test input with broadcast
    def test_broadcast(self):
220

Z
zhiboniu 已提交
221 222 223 224 225 226 227 228 229 230 231 232
        def run(place):
            paddle.disable_static()
            x_np = np.random.random([1, 30, 2]).astype(self.dtype)
            y_np = np.random.random([2, 30, 30]).astype(self.dtype)
            nx_np = np.concatenate((x_np, x_np), axis=0)

            z_sci = scipy_cholesky_solution_batch(y_np, nx_np, upper=self.upper)

            x = paddle.to_tensor(x_np)
            y = paddle.to_tensor(y_np)
            z = paddle.linalg.cholesky_solve(x, y, upper=self.upper)
            self.assertEqual(z_sci.shape, z.numpy().shape)
233
            np.testing.assert_allclose(z_sci, z.numpy(), rtol=1e-05)
Z
zhiboniu 已提交
234 235 236 237 238

        for idx, place in enumerate(self.place):
            run(place)


239
#test condition out of bounds
Z
zhiboniu 已提交
240
class TestCholeskySolveOpError(unittest.TestCase):
241

Z
zhiboniu 已提交
242 243 244 245
    def test_errors(self):
        paddle.enable_static()
        with program_guard(Program(), Program()):
            # The input type of solve_op must be Variable.
246 247 248 249
            x1 = fluid.create_lod_tensor(np.array([[-1]]), [[1]],
                                         fluid.CPUPlace())
            y1 = fluid.create_lod_tensor(np.array([[-1]]), [[1]],
                                         fluid.CPUPlace())
Z
zhiboniu 已提交
250 251
            self.assertRaises(TypeError, paddle.linalg.cholesky_solve, x1, y1)

252
            # The data type of input must be float32 or float64.
Z
zhiboniu 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            x2 = fluid.data(name="x2", shape=[30, 30], dtype="bool")
            y2 = fluid.data(name="y2", shape=[30, 10], dtype="bool")
            self.assertRaises(TypeError, paddle.linalg.cholesky_solve, x2, y2)

            x3 = fluid.data(name="x3", shape=[30, 30], dtype="int32")
            y3 = fluid.data(name="y3", shape=[30, 10], dtype="int32")
            self.assertRaises(TypeError, paddle.linalg.cholesky_solve, x3, y3)

            x4 = fluid.data(name="x4", shape=[30, 30], dtype="float16")
            y4 = fluid.data(name="y4", shape=[30, 10], dtype="float16")
            self.assertRaises(TypeError, paddle.linalg.cholesky_solve, x4, y4)

            # The number of dimensions of input'X must be >= 2.
            x5 = fluid.data(name="x5", shape=[30], dtype="float64")
            y5 = fluid.data(name="y5", shape=[30, 30], dtype="float64")
            self.assertRaises(ValueError, paddle.linalg.cholesky_solve, x5, y5)

            # The number of dimensions of input'Y must be >= 2.
            x6 = fluid.data(name="x6", shape=[30, 30], dtype="float64")
            y6 = fluid.data(name="y6", shape=[30], dtype="float64")
            self.assertRaises(ValueError, paddle.linalg.cholesky_solve, x6, y6)

            # The inner-most 2 dimensions of input'X should be equal to each other
            x7 = fluid.data(name="x7", shape=[2, 3, 4], dtype="float64")
            y7 = fluid.data(name="y7", shape=[2, 4, 3], dtype="float64")
            self.assertRaises(ValueError, paddle.linalg.cholesky_solve, x7, y7)


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