test_lu_unpack_op.py 9.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15
import copy
16
import itertools
17 18
import unittest

19
import numpy as np
20 21 22 23
import scipy
import scipy.linalg
from op_test import OpTest

24 25 26 27 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
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core


def scipy_lu_unpack(A):
    shape = A.shape
    if len(shape) == 2:
        return scipy.linalg.lu(A)
    else:
        preshape = shape[:-2]
        batchsize = np.product(shape) // (shape[-2] * shape[-1])
        Plst = []
        Llst = []
        Ulst = []

        NA = A.reshape((-1, shape[-2], shape[-1]))
        for b in range(batchsize):
            As = NA[b]
            P, L, U = scipy.linalg.lu(As)

            pshape = P.shape
            lshape = L.shape
            ushape = U.shape

            Plst.append(P)
            Llst.append(L)
            Ulst.append(U)

53 54 55 56 57
        return (
            np.array(Plst).reshape(preshape + pshape),
            np.array(Llst).reshape(preshape + lshape),
            np.array(Ulst).reshape(preshape + ushape),
        )
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78


def Pmat_to_perm(Pmat_org, cut):
    Pmat = copy.deepcopy(Pmat_org)
    shape = Pmat.shape
    rows = shape[-2]
    cols = shape[-1]
    batchsize = max(1, np.product(shape[:-2]))
    P = Pmat.reshape(batchsize, rows, cols)
    permmat = []
    for b in range(batchsize):
        permlst = []
        sP = P[b]
        for c in range(min(rows, cols)):
            idx = np.argmax(sP[:, c])
            permlst.append(idx)
            tmp = copy.deepcopy(sP[c, :])
            sP[c, :] = sP[idx, :]
            sP[idx, :] = tmp

        permmat.append(permlst)
79 80 81 82 83 84 85 86 87
    Pivot = (
        np.array(permmat).reshape(
            list(shape[:-2])
            + [
                rows,
            ]
        )
        + 1
    )
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

    return Pivot[..., :cut]


def perm_to_Pmat(perm, dim):
    pshape = perm.shape
    bs = int(np.product(perm.shape[:-1]).item())
    perm = perm.reshape((bs, pshape[-1]))
    oneslst = []
    for i in range(bs):
        idlst = np.arange(dim)
        perm_item = perm[i, :]
        for idx, p in enumerate(perm_item - 1):
            temp = idlst[idx]
            idlst[idx] = idlst[p]
            idlst[p] = temp

        ones = paddle.eye(dim)
        nmat = paddle.scatter(ones, paddle.to_tensor(idlst), ones)
        oneslst.append(nmat)
    return np.array(oneslst).reshape(list(pshape[:-1]) + [dim, dim])


# m > n
class TestLU_UnpackOp(OpTest):
    """
    case 1
    """

    def config(self):
        self.x_shape = [2, 12, 10]
        self.unpack_ludata = True
        self.unpack_pivots = True
        self.dtype = "float64"

    def set_output(self, A):
        sP, sL, sU = scipy_lu_unpack(A)
        self.L = sL
        self.U = sU
        self.P = sP

    def setUp(self):
        self.op_type = "lu_unpack"
131 132
        self.python_api = paddle.tensor.linalg.lu_unpack
        self.python_out_sig = ["Pmat", "L", "U"]
133 134 135 136 137 138 139 140 141 142 143 144
        self.config()
        x = np.random.random(self.x_shape).astype(self.dtype)
        if paddle.in_dynamic_mode():
            xt = paddle.to_tensor(x)
            lu, pivots = paddle.linalg.lu(xt)
            lu = lu.numpy()
            pivots = pivots.numpy()
        else:
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                place = fluid.CPUPlace()
                if core.is_compiled_with_cuda():
                    place = fluid.CUDAPlace(0)
145 146 147
                xv = paddle.fluid.data(
                    name="input", shape=self.x_shape, dtype=self.dtype
                )
148 149
                lu, p = paddle.linalg.lu(xv)
                exe = fluid.Executor(place)
150 151 152 153 154
                fetches = exe.run(
                    fluid.default_main_program(),
                    feed={"input": x},
                    fetch_list=[lu, p],
                )
155 156 157 158 159 160
                lu, pivots = fetches[0], fetches[1]

        self.inputs = {'X': lu, 'Pivots': pivots}

        self.attrs = {
            'unpack_ludata': self.unpack_ludata,
161
            'unpack_pivots': self.unpack_pivots,
162 163 164 165 166 167 168 169 170
        }
        self.set_output(x)
        self.outputs = {
            'Pmat': self.P,
            'L': self.L,
            'U': self.U,
        }

    def test_check_output(self):
171
        self.check_output(check_eager=True)
172 173

    def test_check_grad(self):
174
        self.check_grad(['X'], ['L', 'U'], check_eager=True)
175 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


# m = n
class TestLU_UnpackOp2(TestLU_UnpackOp):
    """
    case 2
    """

    def config(self):
        self.x_shape = [2, 10, 10]
        self.unpack_ludata = True
        self.unpack_pivots = True
        self.dtype = "float64"


# m < n
class TestLU_UnpackOp3(TestLU_UnpackOp):
    """
    case 3
    """

    def config(self):
        self.x_shape = [2, 10, 12]
        self.unpack_ludata = True
        self.unpack_pivots = True
        self.dtype = "float64"


203 204 205 206 207 208 209 210 211 212 213 214 215
# batchsize = 0
class TestLU_UnpackOp4(TestLU_UnpackOp):
    """
    case 4
    """

    def config(self):
        self.x_shape = [10, 12]
        self.unpack_ludata = True
        self.unpack_pivots = True
        self.dtype = "float64"


216
class TestLU_UnpackAPI(unittest.TestCase):
217 218 219
    def setUp(self):
        np.random.seed(2022)

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    def test_dygraph(self):
        def run_lu_unpack_dygraph(shape, dtype):
            if dtype == "float32":
                np_dtype = np.float32
            elif dtype == "float64":
                np_dtype = np.float64
            a = np.random.rand(*shape).astype(np_dtype)
            m = a.shape[-2]
            n = a.shape[-1]
            min_mn = min(m, n)

            places = [fluid.CPUPlace()]
            if core.is_compiled_with_cuda():
                places.append(fluid.CUDAPlace(0))
            for place in places:
                paddle.disable_static(place)

                x = paddle.to_tensor(a, dtype=dtype)
                sP, sL, sU = scipy_lu_unpack(a)
                LU, P = paddle.linalg.lu(x)
                pP, pL, pU = paddle.linalg.lu_unpack(LU, P)

242 243 244
                np.testing.assert_allclose(sU, pU, rtol=1e-05, atol=1e-05)
                np.testing.assert_allclose(sL, pL, rtol=1e-05, atol=1e-05)
                np.testing.assert_allclose(sP, pP, rtol=1e-05, atol=1e-05)
245 246 247 248

        tensor_shapes = [
            (3, 5),
            (5, 5),
249
            (5, 3),  # 2-dim Tensors
250 251 252 253 254
            (2, 3, 5),
            (3, 5, 5),
            (4, 5, 3),  # 3-dim Tensors
            (2, 5, 3, 5),
            (3, 5, 5, 5),
255
            (4, 5, 5, 3),  # 4-dim Tensors
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
        ]
        dtypes = ["float32", "float64"]
        for tensor_shape, dtype in itertools.product(tensor_shapes, dtypes):
            run_lu_unpack_dygraph(tensor_shape, dtype)

    def test_static(self):
        paddle.enable_static()

        def run_lu_static(shape, dtype):
            if dtype == "float32":
                np_dtype = np.float32
            elif dtype == "float64":
                np_dtype = np.float64
            a = np.random.rand(*shape).astype(np_dtype)
            m = a.shape[-2]
            n = a.shape[-1]
            min_mn = min(m, n)

            places = [fluid.CPUPlace()]
            if core.is_compiled_with_cuda():
                places.append(fluid.CUDAPlace(0))
            for place in places:
                with fluid.program_guard(fluid.Program(), fluid.Program()):
                    sP, sL, sU = scipy_lu_unpack(a)

281 282 283
                    x = paddle.fluid.data(
                        name="input", shape=shape, dtype=dtype
                    )
284 285 286
                    lu, p = paddle.linalg.lu(x)
                    pP, pL, pU = paddle.linalg.lu_unpack(lu, p)
                    exe = fluid.Executor(place)
287 288 289 290 291 292 293 294 295 296 297 298 299 300
                    fetches = exe.run(
                        fluid.default_main_program(),
                        feed={"input": a},
                        fetch_list=[pP, pL, pU],
                    )
                    np.testing.assert_allclose(
                        fetches[0], sP, rtol=1e-05, atol=1e-05
                    )
                    np.testing.assert_allclose(
                        fetches[1], sL, rtol=1e-05, atol=1e-05
                    )
                    np.testing.assert_allclose(
                        fetches[2], sU, rtol=1e-05, atol=1e-05
                    )
301 302 303 304

        tensor_shapes = [
            (3, 5),
            (5, 5),
305
            (5, 3),  # 2-dim Tensors
306 307 308 309 310
            (2, 3, 5),
            (3, 5, 5),
            (4, 5, 3),  # 3-dim Tensors
            (2, 5, 3, 5),
            (3, 5, 5, 5),
311
            (4, 5, 5, 3),  # 4-dim Tensors
312 313 314 315 316 317 318 319 320
        ]
        dtypes = ["float32", "float64"]
        for tensor_shape, dtype in itertools.product(tensor_shapes, dtypes):
            run_lu_static(tensor_shape, dtype)


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