test_update_loss_scaling_op.py 14.4 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 unittest
16

17
import numpy as np
18
from eager_op_test import OpTest, convert_float_to_uint16, paddle_static_guard
19

20
import paddle
21
from paddle import fluid
22
from paddle.fluid import core
23
from paddle.static.amp import amp_nn
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
def update_loss_scaling_wrapper(
    x,
    found_inf,
    prev_loss_scaling,
    num_good_steps,
    num_bad_steps,
    incr_every_n_steps,
    decr_every_n_nan_or_inf,
    incr_ratio,
    decr_ratio,
    stop_update=False,
):
    amp_nn.update_loss_scaling(
        [x],
        found_inf,
        prev_loss_scaling,
        num_good_steps,
        num_bad_steps,
        incr_every_n_steps,
        decr_every_n_nan_or_inf,
        incr_ratio,
        decr_ratio,
        stop_update,
    )
50 51 52
    return x, prev_loss_scaling, num_good_steps, num_bad_steps


53 54 55 56
class TestUpdateLossScalingOp(OpTest):
    def setUp(self):
        self.op_type = "update_loss_scaling"
        self.init()
57 58
        self.python_api = update_loss_scaling_wrapper
        self.python_out_sig = [
59 60 61 62
            "out0",
            "LossScaling",
            "OutGoodSteps",
            "OutBadSteps",
63
        ]
64
        found_inf = np.array([False], dtype=np.bool_)
65 66 67 68 69 70 71
        x = np.random.random((1024, 1024)).astype(self.dtype)

        self.inputs = {
            'X': [('x0', x)],
            'FoundInfinite': found_inf,
            'PrevLossScaling': self.prev_loss_scaling,
            'InGoodSteps': self.num_good_steps,
72
            'InBadSteps': self.num_bad_steps,
73 74 75
        }

        self.outputs = {
76
            'Out': [('out0', x)],
77 78
            'LossScaling': self.prev_loss_scaling * self.incr_ratio,
            'OutGoodSteps': self.zero_steps,
79
            'OutBadSteps': self.zero_steps,
80 81 82 83 84
        }

    def init(self):
        self.incr_ratio = 2.0
        self.decr_ratio = 0.8
85 86 87 88
        self.init_dtype()
        self.prev_loss_scaling = np.array([2048]).astype(
            self.loss_scaling_dtype
        )
89 90 91
        self.num_good_steps = np.array([999], dtype=np.int32)
        self.num_bad_steps = np.array([1], dtype=np.int32)
        self.zero_steps = np.array([0], dtype=np.int32)
R
Ryan 已提交
92
        self.stop_update = np.array([False], dtype=np.bool_)
93 94 95 96 97 98 99
        self.attrs = {
            'incr_every_n_steps': 1000,
            'decr_every_n_nan_or_inf': 2,
            'incr_ratio': self.incr_ratio,
            'decr_ratio': self.decr_ratio,
        }

100 101 102 103
    def init_dtype(self):
        self.dtype = np.float32
        self.loss_scaling_dtype = np.float32

104
    def test_check_output(self):
W
wanghuancoder 已提交
105
        self.check_output(no_check_set=['Out'])
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
class TestUpdateLossScalingFP16Op(TestUpdateLossScalingOp):
    def init_dtype(self):
        self.dtype = np.float16
        self.loss_scaling_dtype = np.float32


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support bfloat16",
)
class TestUpdateLossScalingBF16Op(OpTest):
    def init(self):
        self.incr_ratio = 2.0
        self.decr_ratio = 0.8
        self.dtype = np.uint16
        self.np_dtype = "float32"
        self.prev_loss_scaling = np.array([2048]).astype(self.np_dtype)
        self.num_good_steps = np.array([999], dtype=np.int32)
        self.num_bad_steps = np.array([1], dtype=np.int32)
        self.zero_steps = np.array([0], dtype=np.int32)
        self.stop_update = np.array([False], dtype=np.bool_)
        self.attrs = {
            'incr_every_n_steps': 1000,
            'decr_every_n_nan_or_inf': 2,
            'incr_ratio': self.incr_ratio,
            'decr_ratio': self.decr_ratio,
        }

    def setUp(self):
        self.op_type = "update_loss_scaling"
        self.init()
        self.python_api = update_loss_scaling_wrapper
        self.python_out_sig = [
            "out0",
            "LossScaling",
            "OutGoodSteps",
            "OutBadSteps",
        ]
        found_inf = np.array([False], dtype=np.bool_)
        x = np.random.random((1024, 1024)).astype(self.np_dtype)

        self.inputs = {
            'X': [('x0', convert_float_to_uint16(x))],
            'FoundInfinite': found_inf,
            # do not convert
            'PrevLossScaling': self.prev_loss_scaling,
            'InGoodSteps': self.num_good_steps,
            'InBadSteps': self.num_bad_steps,
        }

        self.outputs = {
            'Out': [('out0', convert_float_to_uint16(x))],
            # do not convert
            'LossScaling': self.prev_loss_scaling * self.incr_ratio,
            'OutGoodSteps': self.zero_steps,
            'OutBadSteps': self.zero_steps,
        }

    def test_check_output(self):
        self.check_output_with_place(core.CUDAPlace(0), no_check_set=['Out'])


171 172 173 174
class TestUpdateLossScalingOpBad(TestUpdateLossScalingOp):
    def setUp(self):
        self.op_type = "update_loss_scaling"
        self.init()
175 176
        self.python_api = update_loss_scaling_wrapper
        self.python_out_sig = [
177 178 179 180
            "out0",
            "LossScaling",
            "OutGoodSteps",
            "OutBadSteps",
181
        ]
182
        found_inf = np.array([True], dtype=np.bool_)
183 184 185 186 187 188 189 190 191 192
        x = np.random.random((1024, 1024)).astype(self.dtype)
        i = np.random.randint(0, 1024, 1)
        j = np.random.randint(0, 1024, 1)
        x[i[0]][j[0]] = np.inf

        self.inputs = {
            'X': [('x0', x)],
            'FoundInfinite': found_inf,
            'PrevLossScaling': self.prev_loss_scaling,
            'InGoodSteps': self.num_good_steps,
193
            'InBadSteps': self.num_bad_steps,
194
            'StopUpdate': self.stop_update,
195 196 197 198 199 200
        }

        self.outputs = {
            'Out': [('out0', np.zeros_like(x))],
            'LossScaling': self.prev_loss_scaling * self.decr_ratio,
            'OutGoodSteps': self.zero_steps,
201
            'OutBadSteps': self.zero_steps,
202 203 204
        }

    def test_check_output(self):
W
wanghuancoder 已提交
205
        self.check_output()
206 207 208 209


class TestUpdateLossScalingLayer(unittest.TestCase):
    def loss_scaling_check(self, use_cuda=True, scope=fluid.Scope()):
W
wanghuancoder 已提交
210 211 212
        with paddle_static_guard():
            a = paddle.static.data(
                name="a", shape=[1024, 1024], dtype='float32'
213
            )
W
wanghuancoder 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
            b = paddle.static.data(name="b", shape=[512, 128], dtype='float32')
            x = [a, b]
            found_inf = paddle.static.data(
                name="found_inf", shape=[1], dtype='bool'
            )
            prev_loss_scaling = paddle.static.data(
                name="prev_loss_scaling", shape=[1], dtype='float32'
            )
            num_good_steps = paddle.static.data(
                name="num_good_steps", shape=[1], dtype='int32'
            )
            num_bad_steps = paddle.static.data(
                name="num_bad_steps", shape=[1], dtype='int32'
            )

            a_v = np.random.random([1024, 1024]).astype('float32')
            b_v = np.random.random([512, 128]).astype('float32')
            found_inf_v = np.array([False]).astype('bool')
            prev_loss_scaling_v = np.array([2048]).astype('float32')
            num_good_steps_v = np.array([999], dtype=np.int32)
            num_bad_steps_v = np.array([1], dtype=np.int32)

            incr_every_n_steps = 1000
            decr_every_n_nan_or_inf = 2
            incr_ratio = 2
            decr_ratio = 0.8

            result = amp_nn.update_loss_scaling(
                x,
                found_inf,
                prev_loss_scaling,
                num_good_steps,
                num_bad_steps,
                incr_every_n_steps,
                decr_every_n_nan_or_inf,
                incr_ratio,
                decr_ratio,
                name="update_loss_scaling",
            )

            place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
            exe = fluid.Executor(place)
            with fluid.scope_guard(scope):
                exe.run(fluid.default_startup_program())
                result_v = exe.run(
                    feed={
                        'a': a_v,
                        'b': b_v,
                        'found_inf': found_inf_v,
                        'prev_loss_scaling': prev_loss_scaling_v,
                        'num_good_steps': num_good_steps_v,
                        'num_bad_steps': num_bad_steps_v,
                    },
                    fetch_list=[
                        result,
                        x,
                        found_inf,
                        prev_loss_scaling,
                        num_good_steps,
                        num_bad_steps,
                    ],
                )

277 278 279 280 281 282 283 284 285 286 287 288 289 290
            np.testing.assert_array_equal(result_v[0], a_v)
            np.testing.assert_array_equal(result_v[1], b_v)
            np.testing.assert_array_equal(result_v[0], result_v[2])
            np.testing.assert_array_equal(result_v[1], result_v[3])
            np.testing.assert_array_equal(result_v[4], found_inf_v)
            np.testing.assert_array_equal(
                result_v[5], prev_loss_scaling_v * incr_ratio
            )
            np.testing.assert_array_equal(
                result_v[6], np.zeros_like(num_good_steps_v)
            )
            np.testing.assert_array_equal(
                result_v[7], np.zeros_like(num_bad_steps_v)
            )
291 292

    def loss_scaling_check_inf(self, use_cuda=True, scope=fluid.Scope()):
W
wanghuancoder 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        with paddle_static_guard():
            a = paddle.static.data(
                name="a", shape=[1024, 1024], dtype='float32'
            )
            b = paddle.static.data(name="b", shape=[512, 128], dtype='float32')
            x = [a, b]
            found_inf = paddle.static.data(
                name="found_inf", shape=[1], dtype='bool'
            )
            prev_loss_scaling = paddle.static.data(
                name="prev_loss_scaling", shape=[1], dtype='float32'
            )
            num_good_steps = paddle.static.data(
                name="num_good_steps", shape=[1], dtype='int32'
            )
            num_bad_steps = paddle.static.data(
                name="num_bad_steps", shape=[1], dtype='int32'
310
            )
311

W
wanghuancoder 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
            a_v = np.random.random([1024, 1024]).astype('float32')
            b_v = np.random.random([512, 128]).astype('float32')
            i = np.random.randint(0, 1024, 1)
            j = np.random.randint(0, 1024, 1)
            a_v[i[0]][j[0]] = np.inf
            found_inf_v = np.array([True]).astype('bool')
            prev_loss_scaling_v = np.array([2048]).astype('float32')
            num_good_steps_v = np.array([999], dtype=np.int32)
            num_bad_steps_v = np.array([1], dtype=np.int32)

            incr_every_n_steps = 1000
            decr_every_n_nan_or_inf = 2
            incr_ratio = 2
            decr_ratio = 0.8

            result = amp_nn.update_loss_scaling(
                x,
                found_inf,
                prev_loss_scaling,
                num_good_steps,
                num_bad_steps,
                incr_every_n_steps,
                decr_every_n_nan_or_inf,
                incr_ratio,
                decr_ratio,
                name="update_loss_scaling",
            )
339

W
wanghuancoder 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
            place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
            exe = fluid.Executor(place)
            with fluid.scope_guard(scope):
                exe.run(fluid.default_startup_program())
                result_v = exe.run(
                    feed={
                        'a': a_v,
                        'b': b_v,
                        'found_inf': found_inf_v,
                        'prev_loss_scaling': prev_loss_scaling_v,
                        'num_good_steps': num_good_steps_v,
                        'num_bad_steps': num_bad_steps_v,
                    },
                    fetch_list=[
                        result,
                        x,
                        found_inf,
                        prev_loss_scaling,
                        num_good_steps,
                        num_bad_steps,
                    ],
                )
362 363 364 365 366 367 368 369 370 371 372 373 374 375
            np.testing.assert_array_equal(result_v[0], np.zeros_like(a_v))
            np.testing.assert_array_equal(result_v[1], np.zeros_like(b_v))
            np.testing.assert_array_equal(result_v[2], np.zeros_like(a_v))
            np.testing.assert_array_equal(result_v[3], np.zeros_like(b_v))
            np.testing.assert_array_equal(result_v[4], found_inf_v)
            np.testing.assert_array_equal(
                result_v[5], prev_loss_scaling_v * decr_ratio
            )
            np.testing.assert_array_equal(
                result_v[6], np.zeros_like(num_good_steps_v)
            )
            np.testing.assert_array_equal(
                result_v[7], np.zeros_like(num_bad_steps_v)
            )
376

W
wanghuancoder 已提交
377 378
    def test_loss_scaling_cpu(self):
        with paddle_static_guard():
379 380 381 382
            main = fluid.Program()
            startup = fluid.Program()
            with fluid.unique_name.guard():
                with fluid.program_guard(main, startup):
W
wanghuancoder 已提交
383
                    self.loss_scaling_check(use_cuda=False)
384

W
wanghuancoder 已提交
385 386
    def test_loss_scaling_cpu_inf(self):
        with paddle_static_guard():
387 388 389 390
            main = fluid.Program()
            startup = fluid.Program()
            with fluid.unique_name.guard():
                with fluid.program_guard(main, startup):
W
wanghuancoder 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
                    self.loss_scaling_check_inf(use_cuda=False)

    def test_loss_scaling_gpu(self):
        if fluid.core.is_compiled_with_cuda():
            with paddle_static_guard():
                main = fluid.Program()
                startup = fluid.Program()
                with fluid.unique_name.guard():
                    with fluid.program_guard(main, startup):
                        self.loss_scaling_check(use_cuda=True)

    def test_loss_scaling_gpu_inf(self):
        if fluid.core.is_compiled_with_cuda():
            with paddle_static_guard():
                main = fluid.Program()
                startup = fluid.Program()
                with fluid.unique_name.guard():
                    with fluid.program_guard(main, startup):
                        self.loss_scaling_check_inf(use_cuda=True)
410 411 412 413


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