test_tril_triu_op.py 6.8 KB
Newer Older
W
WuHaobo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   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
import numpy as np
from op_test import OpTest
17
import paddle
W
WuHaobo 已提交
18 19
import paddle.fluid as fluid
import paddle.tensor as tensor
20
from paddle.fluid.framework import Program, program_guard
W
WuHaobo 已提交
21 22 23


class TrilTriuOpDefaultTest(OpTest):
24
    """the base class of other op testcases"""
W
WuHaobo 已提交
25 26 27

    def setUp(self):
        self.initTestCase()
28 29 30
        self.python_api = (
            paddle.tril if self.real_op_type == 'tril' else paddle.triu
        )
W
WuHaobo 已提交
31 32 33 34 35 36 37 38 39
        self.real_np_op = getattr(np, self.real_op_type)

        self.op_type = "tril_triu"
        self.inputs = {'X': self.X}
        self.attrs = {
            'diagonal': self.diagonal,
            'lower': True if self.real_op_type == 'tril' else False,
        }
        self.outputs = {
40 41 42
            'Out': self.real_np_op(self.X, self.diagonal)
            if self.diagonal
            else self.real_np_op(self.X)
W
WuHaobo 已提交
43 44 45
        }

    def test_check_output(self):
F
From00 已提交
46
        self.check_output(check_eager=True)
W
WuHaobo 已提交
47 48

    def test_check_grad_normal(self):
F
From00 已提交
49
        self.check_grad(['X'], 'Out', check_eager=True)
W
WuHaobo 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62

    def initTestCase(self):
        self.real_op_type = np.random.choice(['triu', 'tril'])
        self.diagonal = None
        self.X = np.arange(1, 101, dtype="float64").reshape([10, -1])


def case_generator(op_type, Xshape, diagonal, expected):
    """
    Generate testcases with the params shape of X, diagonal and op_type.
    If arg`expercted` is 'success', it will register an Optest case and expect to pass.
    Otherwise, it will register an API case and check the expect failure.
    """
63 64 65
    cls_name = "{0}_{1}_shape_{2}_diag_{3}".format(
        expected, op_type, Xshape, diagonal
    )
W
WuHaobo 已提交
66
    errmsg = {
67 68 69 70 71 72
        "diagonal: TypeError": "diagonal in {} must be a python Int".format(
            op_type
        ),
        "input: ValueError": "x shape in {} must be at least 2-D".format(
            op_type
        ),
W
WuHaobo 已提交
73 74 75 76
    }

    class FailureCase(unittest.TestCase):
        def test_failure(self):
77 78
            paddle.enable_static()

W
WuHaobo 已提交
79
            data = fluid.data(shape=Xshape, dtype='float64', name=cls_name)
80 81 82
            with self.assertRaisesRegexp(
                eval(expected.split(':')[-1]), errmsg[expected]
            ):
Y
yaoxuefeng 已提交
83
                getattr(tensor, op_type)(x=data, diagonal=diagonal)
W
WuHaobo 已提交
84 85 86

    class SuccessCase(TrilTriuOpDefaultTest):
        def initTestCase(self):
87 88
            paddle.enable_static()

W
WuHaobo 已提交
89 90 91 92 93 94 95 96 97
            self.real_op_type = op_type
            self.diagonal = diagonal
            self.X = np.random.random(Xshape).astype("float64")

    CLASS = locals()['SuccessCase' if expected == "success" else 'FailureCase']
    CLASS.__name__ = cls_name
    globals()[cls_name] = CLASS


98 99 100
# NOTE: meaningful diagonal is [1 - min(H, W), max(H, W) -1]
# test the diagonal just at the border, upper/lower the border,
#     negative/positive integer within range and a zero
W
WuHaobo 已提交
101 102 103 104 105 106 107 108 109
cases = {
    'success': {
        (2, 2, 3, 4, 5): [-100, -3, -1, 0, 2, 4, 100],  # normal shape
        (10, 10, 1, 1): [-100, -1, 0, 1, 100],  # small size of matrix
    },
    'diagonal: TypeError': {
        (20, 20): [
            '2020',
            [20],
110
            {20: 20},
W
WuHaobo 已提交
111 112 113 114 115
            (20, 20),
            20.20,
        ],  # str, list, dict, tuple, float
    },
    'input: ValueError': {
116
        (2020,): [None],
W
WuHaobo 已提交
117 118 119 120 121 122
    },
}
for _op_type in ['tril', 'triu']:
    for _expected, _params in cases.items():
        for _Xshape, _diaglist in _params.items():
            list(
123 124
                map(
                    lambda _diagonal: case_generator(
125 126 127 128 129
                        _op_type, _Xshape, _diagonal, _expected
                    ),
                    _diaglist,
                )
            )
W
WuHaobo 已提交
130 131 132


class TestTrilTriuOpAPI(unittest.TestCase):
133
    """test case by using API and has -1 dimension"""
W
WuHaobo 已提交
134 135

    def test_api(self):
136 137 138 139 140 141 142 143 144 145 146
        paddle.enable_static()

        dtypes = ['float16', 'float32']
        for dtype in dtypes:
            prog = Program()
            startup_prog = Program()
            with program_guard(prog, startup_prog):
                data = np.random.random([1, 9, 9, 4]).astype(dtype)
                x = fluid.data(shape=[1, 9, -1, 4], dtype=dtype, name='x')
                tril_out, triu_out = tensor.tril(x), tensor.triu(x)

147 148 149 150 151
                place = (
                    fluid.CUDAPlace(0)
                    if fluid.core.is_compiled_with_cuda()
                    else fluid.CPUPlace()
                )
152 153 154 155
                exe = fluid.Executor(place)
                tril_out, triu_out = exe.run(
                    fluid.default_main_program(),
                    feed={"x": data},
156 157
                    fetch_list=[tril_out, triu_out],
                )
158 159
                np.testing.assert_allclose(tril_out, np.tril(data), rtol=1e-05)
                np.testing.assert_allclose(triu_out, np.triu(data), rtol=1e-05)
W
WuHaobo 已提交
160

161
    def test_api_with_dygraph(self):
162 163 164 165 166 167 168
        paddle.disable_static()

        dtypes = ['float16', 'float32']
        for dtype in dtypes:
            with fluid.dygraph.guard():
                data = np.random.random([1, 9, 9, 4]).astype(dtype)
                x = fluid.dygraph.to_variable(data)
169 170 171 172
                tril_out, triu_out = (
                    tensor.tril(x).numpy(),
                    tensor.triu(x).numpy(),
                )
173 174
                np.testing.assert_allclose(tril_out, np.tril(data), rtol=1e-05)
                np.testing.assert_allclose(triu_out, np.triu(data), rtol=1e-05)
175

Y
yaoxuefeng 已提交
176
    def test_fluid_api(self):
177 178 179 180 181 182 183 184 185 186 187
        paddle.enable_static()

        dtypes = ['float16', 'float32']
        for dtype in dtypes:
            prog = Program()
            startup_prog = Program()
            with program_guard(prog, startup_prog):
                data = np.random.random([1, 9, 9, 4]).astype(dtype)
                x = fluid.data(shape=[1, 9, -1, 4], dtype=dtype, name='x')
                triu_out = fluid.layers.triu(x)

188 189 190 191 192
                place = (
                    fluid.CUDAPlace(0)
                    if fluid.core.is_compiled_with_cuda()
                    else fluid.CPUPlace()
                )
193
                exe = fluid.Executor(place)
194 195 196 197 198
                triu_out = exe.run(
                    fluid.default_main_program(),
                    feed={"x": data},
                    fetch_list=[triu_out],
                )
Y
yaoxuefeng 已提交
199

W
WuHaobo 已提交
200 201 202

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