test_composite_batch_norm.py 13.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# Copyright (c) 2022 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 utils import SUB_TOLERANCE

import paddle
import paddle.nn.functional as F
22
from paddle import nn
J
Jiabin Yang 已提交
23
from paddle.fluid import core, framework
24
from paddle.incubate.autograd import primapi
J
Jiabin Yang 已提交
25 26 27
from paddle.nn import BatchNorm
from paddle.tensor import ones  # noqa: F401
from paddle.tensor import zeros  # noqa: F401
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 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 132 133 134 135 136 137 138 139

np.random.seed(2023)


def generate_data(shape, dtype="float32"):
    np_data = np.random.random(shape).astype(dtype)
    return np_data


class Attr:
    def __init__(self) -> None:
        self.dtype = "float32"
        self.shape = [4, 6, 12, 24]
        self.training = True
        self.momentum = 0.9
        self.epsilon = 1e-05
        self.data_format = "NCHW"
        self.use_global_stats = None

    def set_dtype(self, dtype) -> None:
        self.dtype = dtype
        return

    def set_shape(self, shape) -> None:
        self.shape = shape
        return

    def set_training(self, training) -> None:
        self.training = training
        return

    def set_momentum(self, momentum) -> None:
        self.momentum = momentum
        return

    def set_epsilon(self, epsilon) -> None:
        self.epsilon = epsilon
        return

    def set_data_format(self, data_format) -> None:
        self.data_format = data_format
        return

    def set_use_global_stats(self, use_global_stats) -> None:
        self.use_global_stats = use_global_stats
        return

    def get_rtol(self, flag):
        rtol = SUB_TOLERANCE[self.dtype][flag].get("rtol")
        return rtol

    def get_atol(self, flag):
        atol = SUB_TOLERANCE[self.dtype][flag].get("atol")
        return atol


attrs = Attr()


def fn(
    x,
    running_mean,
    running_variance,
    weight,
    bias,
    training,
    momentum,
    epsilon,
    data_format,
    use_global_stats,
):
    z = F.batch_norm(
        x,
        running_mean,
        running_variance,
        weight,
        bias,
        training=training,
        momentum=momentum,
        epsilon=epsilon,
        data_format=data_format,
        use_global_stats=use_global_stats,
    )
    return z


def expect_forward(
    inputs,
    running_mean,
    running_variance,
    weight,
    bias,
    training,
    momentum,
    epsilon,
    data_format,
    use_global_stats,
):
    return fn(
        inputs,
        running_mean,
        running_variance,
        weight,
        bias,
        training,
        momentum,
        epsilon,
        data_format,
        use_global_stats,
    )


140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
def cal_static(inputs, running_mean, running_variance, weight, bias, mode=None):
    paddle.enable_static()
    core._set_prim_all_enabled(True)
    startup_program = paddle.static.Program()
    main_program = paddle.static.Program()
    with paddle.static.program_guard(main_program, startup_program):
        x1 = paddle.static.data(
            'x1', shape=inputs.shape, dtype=str(inputs.dtype)
        )
        x2 = paddle.static.data(
            'x2', shape=running_mean.shape, dtype=str(running_mean.dtype)
        )
        x3 = paddle.static.data(
            'x3',
            shape=running_variance.shape,
            dtype=str(running_variance.dtype),
        )
        x4 = paddle.static.data(
            'x4', shape=weight.shape, dtype=str(weight.dtype)
        )
        x5 = paddle.static.data('x5', shape=bias.shape, dtype=str(bias.dtype))
161 162 163 164 165 166 167 168 169
        if attrs.use_global_stats is None:
            attrs.use_global_stats = not attrs.training
            trainable_statistics = False
        else:
            trainable_statistics = not attrs.use_global_stats

        use_run_stat = (
            (not attrs.training) and (not trainable_statistics)
        ) or attrs.use_global_stats
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        y = fn(
            x1,
            x2,
            x3,
            x4,
            x5,
            attrs.training,
            attrs.momentum,
            attrs.epsilon,
            attrs.data_format,
            attrs.use_global_stats,
        )
        blocks = main_program.blocks

        names = dict(
            zip(
                blocks[0].ops[0].output_names, blocks[0].ops[0].output_arg_names
            )
        )
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

        if not use_run_stat:
            vars_list = [
                names[key]
                for key in [
                    "Y",
                    "MeanOut",
                    "VarianceOut",
                    "SavedMean",
                    "SavedVariance",
                ]
            ]
        else:
            vars_list = [
                names[key]
                for key in [
                    "Y",
                    "MeanOut",
                    "VarianceOut",
                ]
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            ]

        fwd_ops = [op.type for op in blocks[0].ops]
        # Ensure that batch_norm in original block
        assert 'batch_norm' in fwd_ops

        if mode:
            primapi.to_prim(blocks)
            fwd_ops_new = [op.type for op in blocks[0].ops]
            # Ensure that batch_norm is splitted into small ops
            assert 'batch_norm' not in fwd_ops_new

    exe = paddle.static.Executor()
    exe.run(startup_program)

    # indeed SavedVariance is 1/sqrt(batch_var+eps)
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    if not use_run_stat:
        Y, MeanOut, VarianceOut, SavedMean, SavedVariance = exe.run(
            main_program,
            feed={
                'x1': inputs,
                'x2': running_mean,
                'x3': running_variance,
                'x4': weight,
                'x5': bias,
            },
            fetch_list=vars_list,
        )
    else:
        Y, MeanOut, VarianceOut = exe.run(
            main_program,
            feed={
                'x1': inputs,
                'x2': running_mean,
                'x3': running_variance,
                'x4': weight,
                'x5': bias,
            },
            fetch_list=vars_list,
        )
249 250
    paddle.disable_static()
    core._set_prim_all_enabled(False)
251 252 253 254
    if not use_run_stat:
        return Y, MeanOut, VarianceOut, SavedMean, SavedVariance
    else:
        return Y, MeanOut, VarianceOut
255 256


257 258 259 260
class TestCompositeBatchNorm(unittest.TestCase):
    def setUp(self):
        self.dtypes = ["float32", "float64"]
        self.training = [False, True]
261
        self.shapes = [[8, 8, 16, 16], [2, 3, 4, 4]]
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
        self.momentum = [0.1, 0.9]
        self.data_formats = ["NCHW", "NHWC"]
        self.use_global_stats = [None, True, False]

    def compare_forward(self):
        np_data = generate_data(attrs.shape, attrs.dtype)
        tensor_data = paddle.to_tensor(np_data)
        if attrs.data_format == 'NCHW':
            C = np_data.shape[1]
        elif attrs.data_format == 'NHWC':
            C = np_data.shape[-1]
        else:
            raise TypeError
        running_mean = paddle.zeros(C, dtype=attrs.dtype)
        running_variance = paddle.ones(C, dtype=attrs.dtype)
        weight = paddle.ones(C, dtype=attrs.dtype) * 2
        bias = paddle.ones(C, dtype=attrs.dtype)

        expect = expect_forward(
            tensor_data,
            running_mean,
            running_variance,
            weight,
            bias,
            attrs.training,
            attrs.momentum,
            attrs.epsilon,
            attrs.data_format,
            attrs.use_global_stats,
        ).numpy()
        np_running_mean = np.zeros(C, dtype=attrs.dtype)
        np_running_variance = np.ones(C, dtype=attrs.dtype)
        np_weight = np.ones(C, dtype=attrs.dtype) * 2
        np_bias = np.ones(C, dtype=attrs.dtype)
296
        res_origin = cal_static(
297
            np_data, np_running_mean, np_running_variance, np_weight, np_bias
298 299 300 301 302 303 304 305 306 307 308 309
        )
        res_prim = cal_static(
            np_data,
            np_running_mean,
            np_running_variance,
            np_weight,
            np_bias,
            mode="prim",
        )

        # prim out vs dygraph mode out
        assert expect.dtype == res_prim[0].dtype
310 311
        np.testing.assert_allclose(
            expect,
312
            res_prim[0],
313 314 315 316
            rtol=attrs.get_rtol("forward"),
            atol=attrs.get_atol("forward"),
        )

317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
        # prim all outs vs origin static all outs
        use_global_stats = attrs.use_global_stats
        if use_global_stats is None:
            use_global_stats = not attrs.training
            trainable_statistics = False
        else:
            trainable_statistics = not use_global_stats
        test_mode = (not attrs.training) and (not trainable_statistics)

        global_stats = test_mode or use_global_stats
        vars_name = [
            "Y",
            "MeanOut",
            "VarianceOut",
            "SavedMean",
            "SavedVariance",
        ]

        assert len(res_origin) == len(res_prim)
        for idx in range(len(res_origin)):
            if global_stats and idx >= 3:
                # In this case saved_mean and saved_var are not expected.
                continue
            origin_item = res_origin[idx]
            prim_item = res_prim[idx]

            assert origin_item.dtype == prim_item.dtype
            rtol = attrs.get_rtol("forward")
            atol = attrs.get_atol("forward")
            if attrs.dtype == "float64" and idx in (1, 2, 3):
                atol = 1e-7
                rtol = 1e-7
            if not isinstance(
                framework._current_expected_place(), core.CPUPlace
            ) and idx in (2, 3):
                atol = 5e-3
                rtol = 5e-3
            np.testing.assert_allclose(
                origin_item,
                prim_item,
                rtol=atol,
                atol=rtol,
                err_msg=f"Check diff failed of output: {vars_name[idx]}",
            )

362 363 364
    def test_forward(self):
        for i in self.training:
            for j in self.dtypes:
365
                for k in self.use_global_stats:
366 367
                    attrs.set_training(i)
                    attrs.set_dtype(j)
368
                    attrs.set_use_global_stats(k)
369 370 371
                    self.compare_forward()

        for n in self.shapes:
372 373 374
            for m in self.momentum:
                for s in self.data_formats:
                    attrs.set_momentum(m)
375 376 377
                    attrs.set_shape(n)
                    attrs.set_data_format(s)
                    self.compare_forward()
378 379


J
Jiabin Yang 已提交
380 381 382 383 384 385 386
def apply_to_static(net, use_cinn):
    build_strategy = paddle.static.BuildStrategy()
    build_strategy.build_cinn_pass = use_cinn
    return paddle.jit.to_static(net, build_strategy=False)


class PrimeNet(paddle.nn.Layer):
387
    def __init__(self, data_layout='NCHW'):
388
        super().__init__()
389 390
        self.conv = nn.Conv2D(2, 4, (3, 3), bias_attr=False)
        self.bn = BatchNorm(4, act="relu", data_layout=data_layout)
J
Jiabin Yang 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

    def forward(self, x):
        y = self.conv(x)
        out = self.bn(y)
        res = F.max_pool2d(out, kernel_size=2, stride=2, padding=0)
        return res


class TestPrimForwardAndBackward(unittest.TestCase):
    """
    Test PrimeNet with @to_static + prim forward + prim backward + cinn v.s Dygraph
    """

    def setUp(self):
        paddle.seed(2022)
406
        self.x = paddle.randn([4, 2, 6, 6], dtype="float32")
J
Jiabin Yang 已提交
407 408
        self.x.stop_gradient = False

409
    def train(self, use_prim, data_layout="NCHW"):
J
Jiabin Yang 已提交
410 411
        core._set_prim_all_enabled(use_prim)
        paddle.seed(2022)
412
        net = PrimeNet(data_layout)
J
Jiabin Yang 已提交
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        sgd = paddle.optimizer.SGD(
            learning_rate=0.1, parameters=net.parameters()
        )

        net = paddle.amp.decorate(models=net, level='O2')

        net = apply_to_static(net, False)
        with paddle.amp.auto_cast(level='O2'):
            out = net(self.x)
            loss = paddle.mean(out)
            loss.backward()
            sgd.step()
            sgd.clear_grad()
            return loss

428
    def test_amp_nchw(self):
J
Jiabin Yang 已提交
429 430 431 432 433 434 435 436 437 438
        if not isinstance(framework._current_expected_place(), core.CPUPlace):
            expected = self.train(False)
            actual = self.train(True)
            np.testing.assert_allclose(
                expected,
                actual,
                rtol=1e-3,
                atol=1e-3,
            )

439 440 441 442 443 444 445 446 447 448 449
    def test_amp_nhwc(self):
        if not isinstance(framework._current_expected_place(), core.CPUPlace):
            expected = self.train(use_prim=False, data_layout="NHWC")
            actual = self.train(use_prim=True, data_layout="NHWC")
            np.testing.assert_allclose(
                expected,
                actual,
                rtol=1e-3,
                atol=1e-3,
            )

J
Jiabin Yang 已提交
450

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
class TestPrimEvalBranch(unittest.TestCase):
    """
    Test eval branch or composite rule of batch_norm.
    """

    def setUp(self):
        paddle.seed(2022)
        self.x = paddle.randn([4, 2, 6, 6], dtype="float32")
        self.x.stop_gradient = False

    def train(self, use_prim):
        core._set_prim_all_enabled(use_prim)
        paddle.seed(2022)
        net = BatchNorm(2, is_test=True)
        net = apply_to_static(net, False)
        out = net(self.x)
        loss = paddle.mean(out)
        return loss

    def test_eval_branch(self):
        expected = self.train(False)
        actual = self.train(True)
        np.testing.assert_allclose(
            expected,
            actual,
            rtol=1e-6,
            atol=1e-6,
        )


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