test_eig_op.py 11.5 KB
Newer Older
L
Lijunhui 已提交
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 16
import unittest

L
Lijunhui 已提交
17
import numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest, skip_check_grad_ci
19

L
Lijunhui 已提交
20 21 22 23 24 25 26
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core


# cast output to complex for numpy.linalg.eig
def cast_to_complex(input, output):
27
    if input.dtype == np.float32:
L
Lijunhui 已提交
28
        output = output.astype(np.complex64)
29
    elif input.dtype == np.float64:
L
Lijunhui 已提交
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 60 61 62 63 64 65
        output = output.astype(np.complex128)
    return output


# define eig backward function for a single square matrix
def eig_backward(w, v, grad_w, grad_v):
    v_tran = np.transpose(v)
    v_tran = np.conjugate(v_tran)
    w_conj = np.conjugate(w)
    w_conj_l = w_conj.reshape(1, w.size)
    w_conj_r = w_conj.reshape(w.size, 1)
    w_conj_2d = w_conj_l - w_conj_r

    vhgv = np.matmul(v_tran, grad_v)
    real_vhgv = np.real(vhgv)
    diag_real = real_vhgv.diagonal()

    diag_2d = diag_real.reshape(1, w.size)
    rhs = v * diag_2d
    mid = np.matmul(v_tran, rhs)
    result = vhgv - mid

    res = np.divide(result, w_conj_2d)
    row, col = np.diag_indices_from(res)
    res[row, col] = 1.0

    tmp = np.matmul(res, v_tran)
    dx = np.linalg.solve(v_tran, tmp)
    return dx


class TestEigOp(OpTest):
    def setUp(self):
        paddle.enable_static()
        paddle.device.set_device("cpu")
        self.op_type = "eig"
W
wanghuancoder 已提交
66
        self.python_api = paddle.linalg.eig
L
Lijunhui 已提交
67 68 69 70 71 72 73 74 75 76
        self.__class__.op_type = self.op_type
        self.init_input()
        self.inputs = {'X': OpTest.np_dtype_to_fluid_dtype(self.x)}
        self.outputs = {'Eigenvalues': self.out[0], 'Eigenvectors': self.out[1]}

    def init_input(self):
        self.set_dtype()
        self.set_dims()
        self.x = np.random.random(self.shape).astype(self.dtype)
        self.out = np.linalg.eig(self.x)
77 78 79 80
        self.out = (
            cast_to_complex(self.x, self.out[0]),
            cast_to_complex(self.x, self.out[1]),
        )
L
Lijunhui 已提交
81 82 83 84 85 86 87 88 89 90

    # for the real input, a customized checker is needed
    def checker(self, outs):
        actual_out_w = outs[0].flatten()
        expect_out_w = self.out[0].flatten()
        actual_out_v = outs[1].flatten()
        expect_out_v = self.out[1].flatten()

        length_w = len(expect_out_w)
        act_w_real = np.sort(
91 92
            np.array([np.abs(actual_out_w[i].real) for i in range(length_w)])
        )
L
Lijunhui 已提交
93
        act_w_imag = np.sort(
94 95
            np.array([np.abs(actual_out_w[i].imag) for i in range(length_w)])
        )
L
Lijunhui 已提交
96
        exp_w_real = np.sort(
97 98
            np.array([np.abs(expect_out_w[i].real) for i in range(length_w)])
        )
L
Lijunhui 已提交
99
        exp_w_imag = np.sort(
100 101
            np.array([np.abs(expect_out_w[i].imag) for i in range(length_w)])
        )
L
Lijunhui 已提交
102 103

        for i in range(length_w):
104 105 106 107 108
            np.testing.assert_allclose(
                act_w_real[i],
                exp_w_real[i],
                rtol=1e-06,
                atol=1e-05,
109 110 111 112 113 114
                err_msg='The eigenvalues real part have diff: \nExpected '
                + str(act_w_real[i])
                + '\n'
                + 'But got: '
                + str(exp_w_real[i]),
            )
115 116 117 118 119
            np.testing.assert_allclose(
                act_w_imag[i],
                exp_w_imag[i],
                rtol=1e-06,
                atol=1e-05,
120 121 122 123 124 125
                err_msg='The eigenvalues image part have diff: \nExpected '
                + str(act_w_imag[i])
                + '\n'
                + 'But got: '
                + str(exp_w_imag[i]),
            )
L
Lijunhui 已提交
126 127 128

        length_v = len(expect_out_v)
        act_v_real = np.sort(
129 130
            np.array([np.abs(actual_out_v[i].real) for i in range(length_v)])
        )
L
Lijunhui 已提交
131
        act_v_imag = np.sort(
132 133
            np.array([np.abs(actual_out_v[i].imag) for i in range(length_v)])
        )
L
Lijunhui 已提交
134
        exp_v_real = np.sort(
135 136
            np.array([np.abs(expect_out_v[i].real) for i in range(length_v)])
        )
L
Lijunhui 已提交
137
        exp_v_imag = np.sort(
138 139
            np.array([np.abs(expect_out_v[i].imag) for i in range(length_v)])
        )
L
Lijunhui 已提交
140 141

        for i in range(length_v):
142 143 144 145 146
            np.testing.assert_allclose(
                act_v_real[i],
                exp_v_real[i],
                rtol=1e-06,
                atol=1e-05,
147 148 149 150 151 152
                err_msg='The eigenvectors real part have diff: \nExpected '
                + str(act_v_real[i])
                + '\n'
                + 'But got: '
                + str(exp_v_real[i]),
            )
153 154 155 156 157
            np.testing.assert_allclose(
                act_v_imag[i],
                exp_v_imag[i],
                rtol=1e-06,
                atol=1e-05,
158 159 160 161 162 163
                err_msg='The eigenvectors image part have diff: \nExpected '
                + str(act_v_imag[i])
                + '\n'
                + 'But got: '
                + str(exp_v_imag[i]),
            )
L
Lijunhui 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

    def set_dtype(self):
        self.dtype = np.complex64

    def set_dims(self):
        self.shape = (10, 10)

    def init_grad(self):
        # grad_w, grad_v complex dtype
        gtype = self.dtype
        if self.dtype == np.float32:
            gtype = np.complex64
        elif self.dtype == np.float64:
            gtype = np.complex128
        self.grad_w = np.ones(self.out[0].shape, gtype)
        self.grad_v = np.ones(self.out[1].shape, gtype)
180 181 182
        self.grad_x = eig_backward(
            self.out[0], self.out[1], self.grad_w, self.grad_v
        )
L
Lijunhui 已提交
183 184

    def test_check_output(self):
185 186 187
        self.check_output_with_place_customized(
            checker=self.checker, place=core.CPUPlace()
        )
L
Lijunhui 已提交
188 189 190

    def test_check_grad(self):
        self.init_grad()
191 192 193 194 195 196
        self.check_grad(
            ['X'],
            ['Eigenvalues', 'Eigenvectors'],
            user_defined_grads=[self.grad_x],
            user_defined_grad_outputs=[self.grad_w, self.grad_v],
        )
L
Lijunhui 已提交
197 198 199 200 201 202 203 204


class TestComplex128(TestEigOp):
    def set_dtype(self):
        self.dtype = np.complex128


@skip_check_grad_ci(
205
    reason="For float dtype, numpy.linalg.eig forward outputs real or complex when input is real, therefore the grad computation may be not the same with paddle.linalg.eig"
L
Lijunhui 已提交
206 207 208 209 210 211 212 213 214 215
)
class TestDouble(TestEigOp):
    def set_dtype(self):
        self.dtype = np.float64

    def test_check_grad(self):
        pass


@skip_check_grad_ci(
216
    reason="For float dtype, numpy.linalg.eig forward outputs real or complex when input is real, therefore the grad computation may be not the same with paddle.linalg.eig"
L
Lijunhui 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229
)
class TestEigBatchMarices(TestEigOp):
    def set_dtype(self):
        self.dtype = np.float64

    def set_dims(self):
        self.shape = (3, 10, 10)

    def test_check_grad(self):
        pass


@skip_check_grad_ci(
230
    reason="For float dtype, numpy.linalg.eig forward outputs real or complex when input is real, therefore the grad computation may be not the same with paddle.linalg.eig"
L
Lijunhui 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
)
class TestFloat(TestEigOp):
    def set_dtype(self):
        self.dtype = np.float32

    def test_check_grad(self):
        pass


class TestEigStatic(TestEigOp):
    def test_check_output_with_place(self):
        paddle.enable_static()
        place = core.CPUPlace()
        input_np = np.random.random([3, 3]).astype('complex')
        expect_val, expect_vec = np.linalg.eig(input_np)
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            input = fluid.data(name="input", shape=[3, 3], dtype='complex')
            act_val, act_vec = paddle.linalg.eig(input)

            exe = fluid.Executor(place)
251 252 253 254 255
            fetch_val, fetch_vec = exe.run(
                fluid.default_main_program(),
                feed={"input": input_np},
                fetch_list=[act_val, act_vec],
            )
256 257 258 259 260
        np.testing.assert_allclose(
            expect_val,
            fetch_val,
            rtol=1e-06,
            atol=1e-06,
261 262 263 264 265 266
            err_msg='The eigen values have diff: \nExpected '
            + str(expect_val)
            + '\n'
            + 'But got: '
            + str(fetch_val),
        )
267 268 269 270 271
        np.testing.assert_allclose(
            np.abs(expect_vec),
            np.abs(fetch_vec),
            rtol=1e-06,
            atol=1e-06,
272 273 274 275 276 277
            err_msg='The eigen vectors have diff: \nExpected '
            + str(np.abs(expect_vec))
            + '\n'
            + 'But got: '
            + str(np.abs(fetch_vec)),
        )
L
Lijunhui 已提交
278 279


280 281 282 283 284 285 286 287 288 289 290
class TestEigDyGraph(unittest.TestCase):
    def test_check_output_with_place(self):
        input_np = np.random.random([3, 3]).astype('complex')
        expect_val, expect_vec = np.linalg.eig(input_np)

        paddle.set_device("cpu")
        paddle.disable_static()

        input_tensor = paddle.to_tensor(input_np)
        fetch_val, fetch_vec = paddle.linalg.eig(input_tensor)

291 292 293 294 295
        np.testing.assert_allclose(
            expect_val,
            fetch_val.numpy(),
            rtol=1e-06,
            atol=1e-06,
296 297 298 299 300 301
            err_msg='The eigen values have diff: \nExpected '
            + str(expect_val)
            + '\n'
            + 'But got: '
            + str(fetch_val),
        )
302 303 304 305 306
        np.testing.assert_allclose(
            np.abs(expect_vec),
            np.abs(fetch_vec.numpy()),
            rtol=1e-06,
            atol=1e-06,
307 308 309 310 311 312
            err_msg='The eigen vectors have diff: \nExpected '
            + str(np.abs(expect_vec))
            + '\n'
            + 'But got: '
            + str(np.abs(fetch_vec.numpy())),
        )
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

    def test_check_grad(self):
        test_shape = [3, 3]
        test_type = 'float64'
        paddle.set_device("cpu")

        input_np = np.random.random(test_shape).astype(test_type)
        real_w, real_v = np.linalg.eig(input_np)

        grad_w = np.ones(real_w.shape, test_type)
        grad_v = np.ones(real_v.shape, test_type)
        grad_x = eig_backward(real_w, real_v, grad_w, grad_v)

        with fluid.dygraph.guard():
            x = fluid.dygraph.to_variable(input_np)
            x.stop_gradient = False
            w, v = paddle.linalg.eig(x)
            (w.sum() + v.sum()).backward()

332 333 334 335 336 337 338 339 340 341 342
        np.testing.assert_allclose(
            np.abs(x.grad.numpy()),
            np.abs(grad_x),
            rtol=1e-05,
            atol=1e-05,
            err_msg='The grad x have diff: \nExpected '
            + str(np.abs(grad_x))
            + '\n'
            + 'But got: '
            + str(np.abs(x.grad.numpy())),
        )
343 344


L
Lijunhui 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
class TestEigWrongDimsError(unittest.TestCase):
    def test_error(self):
        paddle.device.set_device("cpu")
        paddle.disable_static()
        a = np.random.random((3)).astype('float32')
        x = paddle.to_tensor(a)
        self.assertRaises(ValueError, paddle.linalg.eig, x)


class TestEigNotSquareError(unittest.TestCase):
    def test_error(self):
        paddle.device.set_device("cpu")
        paddle.disable_static()
        a = np.random.random((1, 2, 3)).astype('float32')
        x = paddle.to_tensor(a)
        self.assertRaises(ValueError, paddle.linalg.eig, x)


class TestEigUnsupportedDtypeError(unittest.TestCase):
    def test_error(self):
        paddle.device.set_device("cpu")
        paddle.disable_static()
        a = (np.random.random((3, 3)) * 10).astype('int64')
        x = paddle.to_tensor(a)
369
        self.assertRaises(RuntimeError, paddle.linalg.eig, x)
L
Lijunhui 已提交
370 371 372 373


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