“eab9764ced446bda9e36ae23e533dad062c30832”上不存在“src/git@gitcode.net:x649585723/incubator-echarts.git”
test_dropout_op_xpu.py 8.2 KB
Newer Older
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 sys
16

17 18
sys.path.append("..")
import unittest
19

20
import numpy as np
21 22
from op_test_xpu import XPUOpTest

23 24
import paddle
import paddle.fluid as fluid
25
from paddle import _legacy_C_ops
26
from paddle.fluid import Program, program_guard
27

28
paddle.enable_static()
29

30
from xpu.get_test_cover_info import (
31
    XPUOpTestWrapper,
32 33 34
    create_test_class,
    get_xpu_op_support_types,
)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52


class XPUTestDropoutOp(XPUOpTestWrapper):
    def __init__(self):
        self.op_name = 'dropout'
        self.use_dynamic_create_class = False

    class TestDropoutOp(XPUOpTest):
        def setUp(self):
            self.init_inputs_shape()
            self.init_attrs()
            self.dtype = self.in_type
            self.op_type = 'dropout'
            self.inputs = {'X': np.random.random(self.shape).astype(self.dtype)}
            self.attrs = {
                'dropout_prob': self.dropout_prob,
                'fix_seed': self.fix_seed,
                'is_test': self.is_test,
53
                'dropout_implementation': self.dropout_implementation,
54 55 56
            }

            out = self.inputs['X'] * (1.0 - self.dropout_prob)
57
            if not self.is_test:
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
                mask = None
                if self.dropout_prob == 0.0:
                    mask = np.ones(self.shape).astype(self.dtype)
                elif self.dropout_prob == 1.0:
                    mask = np.zeros(self.shape).astype(self.dtype)
                self.outputs = {'Out': out, 'Mask': mask}
            else:
                self.outputs = {'Out': out}

        def init_inputs_shape(self):
            self.shape = [32, 64]

        def init_attrs(self):
            self.__class__.no_need_check_grad = False
            self.dropout_prob = 0.0
            self.fix_seed = True
            self.is_test = False
            self.dropout_implementation = "upscale_in_train"

        def test_check_output(self):
            self.check_output()

        def test_check_grad_normal(self):
81 82
            if (
                hasattr(self.__class__, "no_need_check_grad")
83
                and self.__class__.no_need_check_grad
84
            ):
85 86 87 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 131
                return

            self.check_grad(['X'], 'Out')

    class TestDropoutOpInput1d(TestDropoutOp):
        def init_inputs_shape(self):
            self.shape = [2000]

    class TestDropoutOp2(TestDropoutOp):
        def init_inputs_shape(self):
            self.shape = [32, 64]

        def init_attrs(self):
            self.dropout_prob = 1.0
            self.fix_seed = True
            self.is_test = False
            self.dropout_implementation = "upscale_in_train"

    class TestDropoutOp3(TestDropoutOp):
        def init_inputs_shape(self):
            self.shape = [32, 64, 2]

    class TestDropoutOp4(TestDropoutOp):
        def init_attrs(self):
            self.__class__.no_need_check_grad = True
            self.dropout_prob = 0.35
            self.fix_seed = True
            self.is_test = True
            self.dropout_implementation = "downgrade_in_infer"

    class TestDropoutOp5(TestDropoutOp):
        def init_inputs_shape(self):
            self.shape = [32, 64, 3]

        def init_attrs(self):
            self.__class__.no_need_check_grad = True
            self.dropout_prob = 0.75
            self.fix_seed = True
            self.is_test = True
            self.dropout_implementation = "downgrade_in_infer"

    class TestDropoutOpError(unittest.TestCase):
        def test_errors(self):
            with program_guard(Program(), Program()):

                def test_Variable():
                    # the input of dropout must be Variable.
132 133 134 135 136
                    x1 = fluid.create_lod_tensor(
                        np.array([-1, 3, 5, 5]),
                        [[1, 1, 1, 1]],
                        fluid.CPUPlace(),
                    )
C
ccrrong 已提交
137
                    paddle.nn.functional.dropout(x1, p=0.5)
138 139 140 141 142 143

                self.assertRaises(TypeError, test_Variable)

                def test_dtype():
                    # the input dtype of dropout must be float16 or float32 or float64
                    # float16 only can be set on GPU place
144 145 146
                    x2 = fluid.layers.data(
                        name='x2', shape=[3, 4, 5, 6], dtype="int32"
                    )
C
ccrrong 已提交
147
                    paddle.nn.functional.dropout(x2, p=0.5)
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162

                self.assertRaises(TypeError, test_dtype)

    class TestDropoutCAPI(unittest.TestCase):
        def setUp(self):
            np.random.seed(123)
            self.places = [fluid.CPUPlace()]
            self.places.append(fluid.XPUPlace(0))

        def test_dygraph(self):
            for place in self.places:
                with fluid.dygraph.guard(place):
                    input_np = np.random.random([40, 40]).astype(self.in_type)
                    result_np = input_np
                    input = fluid.dygraph.to_variable(input_np)
163
                    m = paddle.nn.Dropout(p=0.0)
164 165
                    m.eval()
                    result = m(input)
166
                    np.testing.assert_allclose(result.numpy(), result_np)
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

    class TestDropoutBackward(unittest.TestCase):
        def setUp(self):
            np.random.seed(123)
            self.places = [fluid.CPUPlace()]
            self.places.append(fluid.XPUPlace(0))

        def cal_grad_upscale_train(self, mask, prob):
            return mask.astype(self.in_type) / (1 - prob)

        def cal_grad_downscale_in_infer(self, mask):
            return mask.astype(self.in_type)

        def test_backward_downscale_in_infer(self):
            for place in self.places:
                with fluid.dygraph.guard(place):

                    input = paddle.uniform([40, 40], dtype=self.in_type)
                    input.stop_gradient = False
186 187 188
                    out, mask = _legacy_C_ops.dropout(
                        input, 'dropout_prob', 0.5
                    )
189 190
                    out.backward()

191 192
                    np.testing.assert_allclose(
                        input.gradient(),
193 194
                        self.cal_grad_downscale_in_infer(mask.numpy()),
                    )
195 196 197 198 199 200 201 202

        def test_backward_upscale_train(self):
            for place in self.places:
                with fluid.dygraph.guard(place):

                    prob = 0.5
                    input = paddle.uniform([40, 40], dtype=self.in_type)
                    input.stop_gradient = False
203 204 205 206 207 208 209
                    out, mask = _legacy_C_ops.dropout(
                        input,
                        'dropout_prob',
                        prob,
                        "dropout_implementation",
                        "upscale_in_train",
                    )
210 211
                    out.backward()

212 213
                    np.testing.assert_allclose(
                        input.gradient(),
214 215
                        self.cal_grad_upscale_train(mask.numpy(), prob),
                    )
216 217 218 219 220 221 222 223

        def test_backward_upscale_train_2(self):
            for place in self.places:
                with fluid.dygraph.guard(place):

                    prob = 0.3
                    input = paddle.uniform([40, 40], dtype=self.in_type)
                    input.stop_gradient = False
224 225 226 227 228 229 230
                    out, mask = _legacy_C_ops.dropout(
                        input,
                        'dropout_prob',
                        prob,
                        "dropout_implementation",
                        "upscale_in_train",
                    )
231 232
                    out.backward()

233 234
                    np.testing.assert_allclose(
                        input.gradient(),
235 236
                        self.cal_grad_upscale_train(mask.numpy(), prob),
                    )
237 238 239 240 241


support_types = get_xpu_op_support_types('dropout')
for stype in support_types:
    create_test_class(globals(), XPUTestDropoutOp, stype)
242 243 244

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