test_group_norm_op.py 41.6 KB
Newer Older
D
Dun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2018 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

D
Dun 已提交
17
import numpy as np
18
import parameterized as param
W
wanghuancoder 已提交
19 20 21 22 23 24
from eager_op_test import (
    OpTest,
    convert_float_to_uint16,
    paddle_static_guard,
    skip_check_grad_ci,
)
25
from testsuite import create_op
D
Dun 已提交
26

27
import paddle
28 29
from paddle import fluid
from paddle.fluid import core
D
Dun 已提交
30 31


32 33 34
def group_norm_naive(x, scale, bias, epsilon, groups, data_layout):
    if data_layout == "NHWC":
        x = np.transpose(x, (0, 3, 1, 2))  # NHWC => NCHW
D
Dun 已提交
35 36 37 38 39 40 41
    N, C, H, W = x.shape
    G = groups
    x = x.reshape((N * G, -1))
    mean = np.mean(x, axis=1, keepdims=True)
    var = np.var(x, axis=1, keepdims=True)
    output = (x - mean) / np.sqrt(var + epsilon)
    output = output.reshape((N, C, H, W)) * scale.reshape(
42 43
        (-1, 1, 1)
    ) + bias.reshape((-1, 1, 1))
44 45
    if data_layout == "NHWC":
        output = np.transpose(output, (0, 2, 3, 1))  # NCHW => NHWC
D
Dun 已提交
46 47 48
    return output, mean.reshape((N, G)), var.reshape((N, G))


49 50
class TestGroupNormOpError(unittest.TestCase):
    def test_errors(self):
W
wanghuancoder 已提交
51 52
        with paddle_static_guard():
            with fluid.program_guard(fluid.Program(), fluid.Program()):
53

W
wanghuancoder 已提交
54 55 56 57
                def test_x_type():
                    input = np.random.random(2, 100, 3, 5).astype('float32')
                    groups = 2
                    paddle.static.nn.group_norm(input, groups)
58

W
wanghuancoder 已提交
59 60 61 62 63 64 65 66 67 68
                self.assertRaises(TypeError, test_x_type)

                def test_x_dtype():
                    x2 = paddle.static.data(
                        name='x2', shape=[-1, 2, 100, 3, 5], dtype='int32'
                    )
                    groups = 2
                    paddle.static.nn.group_norm(x2, groups)

                self.assertRaises(TypeError, test_x_dtype)
69 70


W
wanghuancoder 已提交
71 72 73 74 75 76 77 78
def group_norm_wrapper(
    input, weight, bias, epsilon=1e-5, num_groups=0, data_format="NCHW"
):
    if data_format == "AnyLayout":
        data_format = "NCDHW"
    return paddle._C_ops.group_norm(
        input, weight, bias, epsilon, num_groups, data_format
    )
79 80


D
Dun 已提交
81 82 83
class TestGroupNormOp(OpTest):
    def setUp(self):
        self.op_type = "group_norm"
W
wanghuancoder 已提交
84 85
        self.python_api = group_norm_wrapper
        self.python_out_sig = ["Y"]
D
Dun 已提交
86
        self.data_format = "NCHW"
87
        self.dtype = np.float64
Z
zhupengyang 已提交
88
        self.shape = (2, 100, 3, 5)
89
        self.attrs = {'epsilon': 1e-5, 'groups': 2, 'data_layout': "NCHW"}
D
Dun 已提交
90 91 92 93
        self.compare_between_place = False
        self.init_test_case()

        input = np.random.random(self.shape).astype(self.dtype)
94 95
        if self.data_format == "NHWC":
            input = np.transpose(input, (0, 2, 3, 1))
D
Dun 已提交
96 97
        scale = np.random.random([self.shape[1]]).astype(self.dtype)
        bias = np.random.random([self.shape[1]]).astype(self.dtype)
98 99 100 101 102 103 104 105
        output, mean, var = group_norm_naive(
            input,
            scale,
            bias,
            self.attrs['epsilon'],
            self.attrs['groups'],
            self.data_format,
        )
D
Dun 已提交
106 107 108 109

        self.inputs = {
            'X': OpTest.np_dtype_to_fluid_dtype(input),
            'Scale': OpTest.np_dtype_to_fluid_dtype(scale),
110
            'Bias': OpTest.np_dtype_to_fluid_dtype(bias),
D
Dun 已提交
111 112
        }
        self.outputs = {'Y': output, 'Mean': mean, 'Variance': var}
113
        self.attrs['data_layout'] = self.data_format
D
Dun 已提交
114 115

    def test_check_output(self):
116 117
        atol = 0
        inplace_atol = 0
D
Dun 已提交
118
        place = core.CPUPlace()
L
Leo Chen 已提交
119 120

        self.check_output_with_place(place, atol=atol)
121

D
Dun 已提交
122 123
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
L
Leo Chen 已提交
124
            # group_norm uses AtomicAdd on CUDAPlace, which do not ensure
125
            # computation order when multiple threads write the same address. So the
L
Leo Chen 已提交
126 127 128 129 130 131
            # result of group_norm is non-deterministic when datatype is float.
            # When inplace_atol is not None, the inplace check uses numpy.allclose
            # to check inplace result instead of numpy.array_equal.
            # Set to inplace_atol to 0, which means the absolute error is 0, and the
            # relative error is 1e-05 in numpy.allclose by default.
            # Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html
132 133 134
            self.check_output_with_place(
                place, atol=atol, inplace_atol=inplace_atol
            )
D
Dun 已提交
135 136

    def do_compare_between_place(self):
137 138
        if not core.is_compiled_with_cuda():
            return
D
Dun 已提交
139 140 141
        place = core.CPUPlace()
        place2 = core.CUDAPlace(0)
        self.scope = core.Scope()
142 143 144
        op_inputs = self.inputs if hasattr(self, "inputs") else {}
        op_outputs = self.outputs if hasattr(self, "outputs") else {}
        op_attrs = self.attrs if hasattr(self, "attrs") else {}
145 146 147
        self.op = create_op(
            self.scope, self.op_type, op_inputs, op_outputs, op_attrs
        )
148
        inputs_to_check = {'X', 'Scale', 'Bias'}
D
Dun 已提交
149
        output_names = 'Y'
150 151 152 153 154 155 156 157 158 159 160 161 162
        cpu_grads = self._get_gradient(
            inputs_to_check, place, output_names, None
        )
        gpu_grads = self._get_gradient(
            inputs_to_check, place2, output_names, None
        )
        self._assert_is_close(
            cpu_grads,
            gpu_grads,
            inputs_to_check,
            0.005,
            "Gradient Check On %s" % str(place),
        )
D
Dun 已提交
163 164 165 166 167

    def test_check_grad(self):
        if self.compare_between_place:
            self.do_compare_between_place()
            return
168

D
Dun 已提交
169
        place = core.CPUPlace()
170
        self.check_grad_with_place(place, {'X', 'Scale', 'Bias'}, 'Y')
D
Dun 已提交
171 172 173 174
        if core.is_compiled_with_cuda():
            place = core.CUDAPlace(0)
            self.check_grad_with_place(
                place,
175
                {'X', 'Scale', 'Bias'},
176 177
                'Y',
            )
D
Dun 已提交
178 179 180 181 182

    def init_test_case(self):
        pass


183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_float16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support the bfloat16",
)
class TestGroupNormFP16OP(TestGroupNormOp):
    def test_check_output(self):
        atol = 1e-3
        inplace_atol = 1e-3

        place = core.CUDAPlace(0)
        # group_norm uses AtomicAdd on CUDAPlace, which do not ensure
        # computation order when multiple threads write the same address. So the
        # result of group_norm is non-deterministic when datatype is float.
        # When inplace_atol is not None, the inplace check uses numpy.allclose
        # to check inplace result instead of numpy.array_equal.
        # Set to inplace_atol to 0, which means the absolute error is 0, and the
        # relative error is 1e-05 in numpy.allclose by default.
        # Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html
        self.check_output_with_place(place)

    def test_check_grad(self):
        if self.compare_between_place:
            return

        place = core.CUDAPlace(0)
209
        self.check_grad_with_place(place, {'X', 'Scale', 'Bias'}, 'Y')
210 211 212 213 214 215 216 217 218 219 220 221 222

    def init_test_case(self):
        self.dtype = np.float16


@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 the bfloat16",
)
class TestGroupNormBF16Op(OpTest):
    def setUp(self):
        self.op_type = "group_norm"
W
wanghuancoder 已提交
223 224
        self.python_api = group_norm_wrapper
        self.python_out_sig = ["Y"]
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
        self.data_format = "NCHW"
        self.dtype = np.uint16
        self.shape = (2, 100, 3, 5)
        self.attrs = {'epsilon': 1e-5, 'groups': 2, 'data_layout': "NCHW"}
        self.compare_between_place = False
        self.init_test_case()

        input = np.random.random(self.shape).astype(np.float32)
        if self.data_format == "NHWC":
            input = np.transpose(input, (0, 2, 3, 1))
        scale = np.random.random([self.shape[1]]).astype(np.float32)
        bias = np.random.random([self.shape[1]]).astype(np.float32)
        output, mean, var = group_norm_naive(
            input,
            scale,
            bias,
            self.attrs['epsilon'],
            self.attrs['groups'],
            self.data_format,
        )

        self.inputs = {
            'X': convert_float_to_uint16(input),
            'Scale': convert_float_to_uint16(scale),
            'Bias': convert_float_to_uint16(bias),
        }
        self.outputs = {'Y': output, 'Mean': mean, 'Variance': var}
        self.attrs['data_layout'] = self.data_format

    def test_check_output(self):
        atol = 1e-2
        inplace_atol = 1e-2

        place = core.CUDAPlace(0)
        # group_norm uses AtomicAdd on CUDAPlace, which do not ensure
        # computation order when multiple threads write the same address. So the
        # result of group_norm is non-deterministic when datatype is float.
        # When inplace_atol is not None, the inplace check uses numpy.allclose
        # to check inplace result instead of numpy.array_equal.
        # Set to inplace_atol to 0, which means the absolute error is 0, and the
        # relative error is 1e-05 in numpy.allclose by default.
        # Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html
        self.check_output_with_place(place)

    def test_check_grad(self):
        if self.compare_between_place:
            return

        place = core.CUDAPlace(0)
274
        self.check_grad_with_place(place, {'X', 'Scale', 'Bias'}, 'Y')
275 276 277 278 279

    def init_test_case(self):
        pass


D
Dun 已提交
280 281 282 283 284
class TestGroupNormOp1(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 1


285 286 287 288 289 290 291 292 293 294 295
class TestGroupNormFP16Op1(TestGroupNormFP16OP):
    def init_test_case(self):
        self.attrs['groups'] = 1
        self.dtype = np.float16


class TestGroupNormBF16Op1(TestGroupNormBF16Op):
    def init_test_case(self):
        self.attrs['groups'] = 1


D
Dun 已提交
296 297 298 299 300
class TestGroupNormOp2(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 4


301 302 303 304 305 306 307 308 309 310 311
class TestGroupNormFP16Op2(TestGroupNormFP16OP):
    def init_test_case(self):
        self.attrs['groups'] = 4
        self.dtype = np.float16


class TestGroupNormBF16Op2(TestGroupNormBF16Op):
    def init_test_case(self):
        self.attrs['groups'] = 4


D
Dun 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
class TestGroupNormOpBigEps1(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 1
        self.attrs['epsilon'] = 0.5


class TestGroupNormOpBigEps2(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 4
        self.attrs['epsilon'] = 0.5


class TestGroupNormOpBigEps3(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['epsilon'] = 0.5


329
@skip_check_grad_ci(
330
    reason='''This test case is used to ensure whether the gradient checking results between CPU and GPU
331 332
            are consistent when using the same inputs, thus, it doesn't need to call check_grad.'''
)
D
Dun 已提交
333 334 335 336 337 338 339
class TestGroupNormOpLargeData(TestGroupNormOp):
    def init_test_case(self):
        self.shape = (2, 32, 64, 64)
        self.attrs['groups'] = 8
        self.compare_between_place = True


340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
class TestGroupNormOp1_With_NHWC(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 1
        self.data_format = "NHWC"


class TestGroupNormOp2_With_NHWC(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 4
        self.data_format = "NHWC"


class TestGroupNormOpBigEps1_With_NHWC(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 1
        self.attrs['epsilon'] = 0.5
        self.data_format = "NHWC"


class TestGroupNormOpBigEps2_With_NHWC(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['groups'] = 4
        self.attrs['epsilon'] = 0.5
        self.data_format = "NHWC"


class TestGroupNormOpBigEps3_With_NHWC(TestGroupNormOp):
    def init_test_case(self):
        self.attrs['epsilon'] = 0.5
        self.data_format = "NHWC"


372
@skip_check_grad_ci(
373
    reason='''This test case is used to ensure whether the gradient checking results between CPU and GPU
374 375
            are consistent when using the same inputs, thus, it doesn't need to call check_grad.'''
)
376 377 378 379 380 381 382 383
class TestGroupNormOpLargeData_With_NHWC(TestGroupNormOp):
    def init_test_case(self):
        self.shape = (2, 64, 32, 32)  # NCHW
        self.attrs['groups'] = 8
        self.data_format = "NHWC"
        self.compare_between_place = True


384
class TestGroupNormAPI_With_NHWC(unittest.TestCase):
385
    def test_case1(self):
W
wanghuancoder 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398
        with paddle_static_guard():
            data1 = paddle.static.data(
                name='data1', shape=[None, 3, 3, 4], dtype='float64'
            )
            out1 = paddle.static.nn.group_norm(
                input=data1, groups=2, data_layout="NHWC"
            )
            data2 = paddle.static.data(
                name='data2', shape=[None, 4, 3, 3], dtype='float64'
            )
            out2 = paddle.static.nn.group_norm(
                input=data2, groups=2, data_layout="NCHW"
            )
399

W
wanghuancoder 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
            data1_np = np.random.random((2, 3, 3, 4)).astype("float64")
            data2_np = np.random.random((2, 4, 3, 3)).astype("float64")
            scale = np.array([1]).astype("float64")
            bias = np.array([0]).astype("float64")

            place = core.CPUPlace()
            exe = fluid.Executor(place)
            results = exe.run(
                fluid.default_main_program(),
                feed={"data1": data1_np, "data2": data2_np},
                fetch_list=[out1, out2],
                return_numpy=True,
            )
            expect_res1 = group_norm_naive(
                data1_np,
                scale,
                bias,
                epsilon=1e-5,
                groups=2,
                data_layout="NHWC",
            )
            expect_res2 = group_norm_naive(
                data2_np,
                scale,
                bias,
                epsilon=1e-5,
                groups=2,
                data_layout="NCHW",
            )
            np.testing.assert_allclose(results[0], expect_res1[0], rtol=1e-05)
            np.testing.assert_allclose(results[1], expect_res2[0], rtol=1e-05)
431

432

433
class TestGroupNormException(unittest.TestCase):
434
    # data_layout is not NHWC or NCHW
435
    def test_exception(self):
W
wanghuancoder 已提交
436 437 438
        with paddle_static_guard():
            data = paddle.static.data(
                name='data', shape=[None, 3, 3, 4], dtype="float64"
439
            )
440

W
wanghuancoder 已提交
441 442 443 444 445 446
            def attr_data_format():
                out = paddle.static.nn.group_norm(
                    input=data, groups=2, data_layout="NDHW"
                )

            self.assertRaises(ValueError, attr_data_format)
447 448


449
class TestGroupNormEager(unittest.TestCase):
450
    def test_dygraph_api(self):
451 452 453 454
        # not supported float64
        # only support float32
        self.dtype = np.float32

455 456 457 458 459 460
        self.shape = (8, 32, 32)
        input = np.random.random(self.shape).astype(self.dtype)

        with fluid.dygraph.guard():
            tensor_1 = fluid.dygraph.to_variable(input)
            tensor_1.stop_gradient = False
461
            groupNorm = paddle.nn.GroupNorm(num_channels=32, num_groups=4)
462 463
            ret1 = groupNorm(tensor_1)
            ret1.backward()
464 465 466 467 468 469 470 471 472
            tensor_eager_1 = fluid.dygraph.to_variable(input)
            tensor_eager_1.stop_gradient = False
            groupNorm_eager = paddle.nn.GroupNorm(num_channels=32, num_groups=4)
            ret2 = groupNorm_eager(tensor_eager_1)
            ret2.backward()
            self.assertEqual(
                (tensor_1.grad.numpy() == tensor_eager_1.grad.numpy()).all(),
                True,
            )
473

W
Wang Bojun 已提交
474 475 476 477 478 479 480
        self.dtype = np.float32
        self.shape = (8, 32, 32)
        input = np.random.random(self.shape).astype(self.dtype)

        with fluid.dygraph.guard():
            tensor_1 = fluid.dygraph.to_variable(input)
            tensor_1.stop_gradient = False
481
            groupNorm = paddle.nn.GroupNorm(num_channels=32, num_groups=4)
W
Wang Bojun 已提交
482 483
            ret1 = groupNorm(tensor_1)
            ret1.backward()
484 485 486 487 488 489 490 491 492
            tensor_eager_1 = fluid.dygraph.to_variable(input)
            tensor_eager_1.stop_gradient = False
            groupNorm_eager = paddle.nn.GroupNorm(num_channels=32, num_groups=4)
            ret2 = groupNorm_eager(tensor_eager_1)
            ret2.backward()
            self.assertEqual(
                (tensor_1.grad.numpy() == tensor_eager_1.grad.numpy()).all(),
                True,
            )
W
Wang Bojun 已提交
493 494 495 496


class TestGroupNormEager_fp16(unittest.TestCase):
    def test_dygraph_api(self):
497 498
        # not supported float16
        # only support float32
W
Wang Bojun 已提交
499
        self.dtype = np.float32
500

W
Wang Bojun 已提交
501 502 503 504 505 506
        self.shape = (8, 32, 32)
        input = np.random.random(self.shape).astype(self.dtype)

        with fluid.dygraph.guard():
            tensor_1 = fluid.dygraph.to_variable(input)
            tensor_1.stop_gradient = False
507
            groupNorm = paddle.nn.GroupNorm(num_channels=32, num_groups=4)
W
Wang Bojun 已提交
508 509
            ret1 = groupNorm(tensor_1)
            ret1.backward()
510 511 512 513 514 515 516 517 518
            tensor_eager_1 = fluid.dygraph.to_variable(input)
            tensor_eager_1.stop_gradient = False
            groupNorm_eager = paddle.nn.GroupNorm(num_channels=32, num_groups=4)
            ret2 = groupNorm_eager(tensor_eager_1)
            ret2.backward()
            self.assertEqual(
                (tensor_1.grad.numpy() == tensor_eager_1.grad.numpy()).all(),
                True,
            )
W
Wang Bojun 已提交
519 520


521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
places = [paddle.CPUPlace()]
if paddle.is_compiled_with_cuda():
    places.append(paddle.CUDAPlace(0))


class PrimNet(paddle.nn.Layer):
    def __init__(
        self,
        num_groups,
        num_channels,
        scale,
        bias,
        epsilon=1e-05,
        data_format='NCHW',
        name=None,
    ):
        super().__init__()
        self.func = paddle.nn.GroupNorm(
            num_groups, num_channels, epsilon, False, False, data_format, name
        )
        paddle.assign(scale, self.func.weight)
        paddle.assign(bias, self.func.bias)

    def forward(self, x):
        out = self.func(x)
        return out


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=build_strategy)


# The original GroupNorm cannot support NHWC format
@param.parameterized_class(
    (
        'name',
        'shape',
        'epsilon',
        'groups',
        'data_format',
        'places',
        'dtype',
        'threshold_list',
        'special_threshold',
    ),
    (
        (
            'test0',
            (2, 100, 3, 5),
            1e-5,
            2,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
        (
            'test1',
            (2, 100, 3, 5),
            1e-5,
            1,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
        (
            'test2',
            (2, 100, 3, 5),
            1e-5,
            4,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
        (
            'bigeps1',
            (2, 100, 3, 5),
            0.5,
            1,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
        (
            'bigeps2',
            (2, 100, 3, 5),
            0.5,
            4,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
        (
            'bigeps3',
            (2, 100, 3, 5),
            0.5,
            2,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
        (
            'largedata',
            (2, 32, 64, 64),
            1e-5,
            4,
            'NCHW',
            places,
            'float32',
            [
                [5e-5, 5e-5, 5e-5],  # cpu thresholds for static, jit, jit_cinn
                [1e-5, 1e-5, 1e-5],
            ],  # gpu thresholds for static, jit, jit_cinn
            [
                5e-2,
                5e-3,
            ],  # threshold for cpu x_grad (5e-2), cpu scale_grad (5e-2) and gpu scale_grad (5e-3)
        ),
        (
            'test0_fp64',
            (2, 100, 3, 5),
            1e-5,
            2,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [
                5e-14,
                2e-14,
            ],  # threshold for cpu x_grad, cpu scale_grad and gpu scale_grad
        ),
        (
            'test1_fp64',
            (2, 100, 3, 5),
            1e-5,
            1,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [
                5e-14,
                2e-14,
            ],  # threshold for cpu x_grad, cpu scale_grad and gpu scale_grad
        ),
        (
            'test2_fp64',
            (2, 100, 3, 5),
            1e-5,
            4,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [5e-14, 2e-14],  # threshold for scale_grad on cpu and gpu
        ),
        (
            'bigeps1_fp64',
            (2, 100, 3, 5),
            0.5,
            1,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [5e-14, 2e-14],  # threshold for scale_grad on cpu and gpu
        ),
        (
            'bigeps2_fp64',
            (2, 100, 3, 5),
            0.5,
            4,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [5e-14, 2e-14],  # threshold for scale_grad on cpu and gpu
        ),
        (
            'bigeps3_fp64',
            (2, 100, 3, 5),
            0.5,
            2,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [5e-14, 2e-14],  # threshold for scale_grad on cpu and gpu
        ),
        (
            'largedata_fp64',
            (2, 32, 64, 64),
            1e-5,
            4,
            'NCHW',
            places,
            'float64',
            [
                [
                    5e-14,
                    5e-14,
                    5e-14,
                ],  # cpu thresholds for static, jit, jit_cinn
                [1e-14, 1e-14, 1e-14],
            ],  # gpu thresholds for static, jit, jit_cinn
            [5e-11, 5e-12],  # threshold for scale_grad on cpu and gpu
        ),
        (
            'test0_fp16',
            (2, 100, 3, 5),
            1e-5,
            2,
            'NCHW',
            places,
            'float16',
            [[1e-3, 1e-3, 1e-3]],  # gpu thresholds for static, jit, jit_cinn
            None,
        ),
    ),
)
class TestCompositeGroupNorm(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        core._set_prim_all_enabled(True)

    @classmethod
    def tearDownClass(cls):
        core._set_prim_all_enabled(False)

    def setUp(self):
        np.random.seed(1234)
        self.fwd_desire = []
        self.rev_desire = []
        self.x = np.random.random(self.shape).astype(self.dtype)
        self.scale = np.random.random([self.shape[1]]).astype(self.dtype)
        self.bias = np.random.random([self.shape[1]]).astype(self.dtype)
        self.num_channels = self.shape[1]

        if self.dtype == 'float16':
            self.places = []
            if paddle.is_compiled_with_cuda():
                self.places.append(paddle.CUDAPlace(0))

        self.static_fwd_desire = []
        self.static_rev_desire = []
        for place in self.places:
            fwd_desire, rev_desire = self.get_eager_desire(place)
            self.fwd_desire.append(fwd_desire.numpy())
            self.rev_desire.append(rev_desire.numpy())
            self.static_fwd_desire.append([])
            self.static_rev_desire.append([])
            fwd, rev = self.get_static_desire(place)
            self.static_fwd_desire[-1].append(fwd[0])
            self.static_fwd_desire[-1].append(fwd[1])
            self.static_fwd_desire[-1].append(fwd[2])
            self.static_rev_desire[-1].append(rev[0])
            self.static_rev_desire[-1].append(rev[1])
            self.static_rev_desire[-1].append(rev[2])

    def get_eager_desire(self, place):
        if isinstance(place, fluid.CPUPlace):
            paddle.set_device("cpu")
        if isinstance(place, fluid.CUDAPlace):
            paddle.set_device("gpu")
        core.set_prim_eager_enabled(False)
        paddle.disable_static()
        input_ = paddle.to_tensor(
            data=self.x, dtype=self.dtype, place=place, stop_gradient=False
        )
        scale_ = paddle.to_tensor(
            data=self.scale, dtype=self.dtype, place=place, stop_gradient=False
        )
        bias_ = paddle.to_tensor(
            data=self.bias, dtype=self.dtype, place=place, stop_gradient=False
        )
        group_norm = paddle.nn.GroupNorm(
            self.groups,
            self.num_channels,
            self.epsilon,
            False,
            False,
            self.data_format,
        )
        paddle.assign(scale_, group_norm.weight)
        paddle.assign(bias_, group_norm.bias)
        output = group_norm(input_)
        grad = paddle.grad(output, input_)

        return output, grad[0]

    def get_static_desire(self, place):
        core._set_prim_all_enabled(False)
        paddle.enable_static()
        if isinstance(place, fluid.CPUPlace):
            paddle.set_device("cpu")
        if isinstance(place, fluid.CUDAPlace):
            paddle.set_device("gpu")

        mp, sp = paddle.static.Program(), paddle.static.Program()
        with paddle.static.program_guard(mp, sp):
            input_ = paddle.static.data(
                'x', shape=self.x.shape, dtype=self.x.dtype
            )
            input_.stop_gradient = False

            scale_ = paddle.static.data(
                'scale_', shape=self.scale.shape, dtype=self.bias.dtype
            )
            scale_.stop_gradient = False

            bias_ = paddle.static.data(
                'bias_', shape=self.bias.shape, dtype=self.x.dtype
            )
            bias_.stop_gradient = False

            group_norm = paddle.nn.GroupNorm(
                self.groups,
                self.num_channels,
                self.epsilon,
                False,
                False,
                self.data_format,
            )
            group_norm.weight.stop_gradient = False
            group_norm.bias.stop_gradient = False

            paddle.assign(scale_, group_norm.weight)
            paddle.assign(bias_, group_norm.bias)
            output = group_norm(input_)

            blocks = mp.blocks

            names = dict(
                zip(
                    blocks[0].ops[2].output_names,
                    blocks[0].ops[2].output_arg_names,
                )
            )
            vars_list = [
                names[key]
                for key in [
                    "Y",
                    "Mean",
                    "Variance",
                ]
            ]

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

            if core._is_fwd_prim_enabled():
                paddle.incubate.autograd.primapi.to_prim(mp.blocks)
                fwd_ops_new = [op.type for op in blocks[0].ops]
                # Ensure that group_norm is splitted into small ops
                assert 'group_norm' not in fwd_ops_new

            grads = paddle.static.gradients([output], [input_, scale_, bias_])

        exe = paddle.static.Executor(place)
        exe.run(sp)
        out_list = exe.run(
            mp,
            feed={
                input_.name: self.x,
                scale_.name: self.scale,
                bias_.name: self.bias,
            },
            fetch_list=vars_list + [grads],
        )
        paddle.disable_static()
        core._set_prim_all_enabled(True)

        return out_list[:3], out_list[3:]

    def test_static_comp(self):
        paddle.enable_static()
        mps = []
        fwd_actual = []
        rev_actual = []
        if len(self.places) < 1:
            return

        with paddle.fluid.framework._static_guard():
            for place in self.places:
                fwd_actual.append([])
                rev_actual.append([])
                mp, sp = paddle.static.Program(), paddle.static.Program()
                with paddle.static.program_guard(mp, sp):
                    input_ = paddle.static.data(
                        'x', shape=self.x.shape, dtype=self.x.dtype
                    )
                    input_.stop_gradient = False

                    scale_ = paddle.static.data(
                        'scale_', shape=self.scale.shape, dtype=self.bias.dtype
                    )
                    scale_.stop_gradient = False

                    bias_ = paddle.static.data(
                        'bias_', shape=self.bias.shape, dtype=self.x.dtype
                    )
                    bias_.stop_gradient = False

                    group_norm = paddle.nn.GroupNorm(
                        self.groups,
                        self.num_channels,
                        self.epsilon,
                        False,
                        False,
                        self.data_format,
                    )
                    group_norm.weight.stop_gradient = False
                    group_norm.bias.stop_gradient = False

                    paddle.assign(scale_, group_norm.weight)
                    paddle.assign(bias_, group_norm.bias)
                    output = group_norm(input_)

                    blocks = mp.blocks
                    names = dict(
                        zip(
                            blocks[0].ops[2].output_names,
                            blocks[0].ops[2].output_arg_names,
                        )
                    )
                    vars_list = [
                        names[key]
                        for key in [
                            "Y",
                            "Mean",
                            "Variance",
                        ]
                    ]

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

                    if core._is_fwd_prim_enabled():
                        paddle.incubate.autograd.primapi.to_prim(mp.blocks)
                        fwd_ops_new = [op.type for op in blocks[0].ops]
                        # Ensure that group_norm is splitted into small ops
                        assert 'group_norm' not in fwd_ops_new

                    grads = paddle.static.gradients(
                        output, [input_, scale_, bias_]
                    )
                exe = paddle.static.Executor(place)
                exe.run(sp)
                out_list = exe.run(
                    mp,
                    feed={
                        input_.name: self.x,
                        scale_.name: self.scale,
                        bias_.name: self.bias,
                    },
                    fetch_list=vars_list + [grads],
                )
                fwd_actual[-1].append(out_list[0])
                fwd_actual[-1].append(out_list[1])
                fwd_actual[-1].append(out_list[2])
                rev_actual[-1].append(out_list[3])
                rev_actual[-1].append(out_list[4])
                rev_actual[-1].append(out_list[5])
                mps.append(mp)

        vars_name = [
            "Y",
            "Mean",
            "Variance",
            "X_grad",
            "Scale_grad",
            "Bias_grad",
        ]

        for i in range(len(self.places)):
            self.assertTrue(
                'group_norm' not in [op.type for op in mps[i].block(0).ops]
            )
            atol = self.threshold_list[i][0]
            rtol = self.threshold_list[i][0]
            for j in range(len(self.static_fwd_desire[i])):
                # in float16 type, Y is float16, mean and var are float16
                # so check mean and var with float32 gpu threshold
                if self.dtype == 'float16' and j > 0:
                    atol = 1e-5
                    rtol = 1e-5

                np.testing.assert_allclose(
                    self.static_fwd_desire[i][j],
                    fwd_actual[i][j],
                    rtol=rtol,
                    atol=atol,
                    err_msg=f"Check diff failed of place:{self.places[i]}, output: {vars_name[j]}",
                )
                max_abs_diff = np.max(
                    np.abs(self.static_fwd_desire[i][j] - fwd_actual[i][j])
                )
                print(
                    self.shape,
                    self.dtype,
                    self.places[i],
                    vars_name[j],
                    max_abs_diff,
                )
            # compare with eager_desire
            np.testing.assert_allclose(
                self.fwd_desire[i],
                fwd_actual[i][0],
                rtol=rtol,
                atol=atol,
                err_msg=f"Check diff failed with fwd_eager:{self.places[i]}",
            )

            for j in range(len(self.static_rev_desire[i])):
                # TODO: fix the diff between cpu and gpu grad is large in original op
                # now use larger threshold when testing cpu grads to bypass cpu grad test
                if self.special_threshold is not None and j <= 1:
                    atol = self.special_threshold[i]
                    rtol = self.special_threshold[i]
                else:
                    atol = self.threshold_list[i][0]
                    rtol = self.threshold_list[i][0]

                max_abs_diff = np.max(
                    np.abs(self.static_rev_desire[i][j] - rev_actual[i][j])
                )

                print(
                    self.shape,
                    self.dtype,
                    self.places[i],
                    vars_name[j + 3],
                    max_abs_diff,
                )

                np.testing.assert_allclose(
                    self.static_rev_desire[i][j],
                    rev_actual[i][j],
                    rtol=rtol,
                    atol=atol,
                    err_msg=f"Check diff failed of place:{self.places[i]}, output: {vars_name[j + 3]}",
                )

            # TODO: fix the diff between cpu and gpu grad is large in original op
            # now use larger threshold when testing cpu grads to bypass cpu grad test
            if self.special_threshold is not None and i == 0:
                atol = self.special_threshold[i]
                rtol = self.special_threshold[i]
            # compare with eager_desire
            np.testing.assert_allclose(
                self.rev_desire[i],
                rev_actual[i][0],
                rtol=rtol,
                atol=atol,
                err_msg=f"Check diff failed with rev_eager:{self.places[i]}",
            )

        paddle.disable_static()

    def test_jit_comp(self):
        fwd_actual = []
        rev_actual = []
        for place in self.places:
            input_ = paddle.to_tensor(
                data=self.x, dtype=self.dtype, place=place, stop_gradient=False
            )
            scale_ = paddle.to_tensor(
                data=self.scale,
                dtype=self.dtype,
                place=place,
                stop_gradient=False,
            )
            bias_ = paddle.to_tensor(
                data=self.bias,
                dtype=self.dtype,
                place=place,
                stop_gradient=False,
            )
            net = PrimNet(
                self.groups,
                self.num_channels,
                scale_,
                bias_,
                self.epsilon,
                self.data_format,
            )
            net = apply_to_static(net, False)
            output = net(input_)
            grad = paddle.grad(output, input_)
            fwd_actual.append(output.numpy())
            rev_actual.append(grad[0].numpy())

        for i in range(len(self.places)):
            atol = self.threshold_list[i][1]
            rtol = self.threshold_list[i][1]
            np.testing.assert_allclose(
                self.fwd_desire[i],
                fwd_actual[i],
                rtol=rtol,
                atol=atol,
                err_msg='%s jit fwd' % self.places[i],
            )

            # TODO: fix the diff between cpu and gpu grad is large in original op
            # now use larger threshold when testing cpu grads to bypass cpu grad test
            if self.special_threshold is not None:
                atol = self.special_threshold[i]
                rtol = self.special_threshold[i]

            np.testing.assert_allclose(
                self.rev_desire[i],
                rev_actual[i],
                rtol=rtol,
                atol=atol,
                err_msg='%s jit rev' % self.places[i],
            )

    def test_jit_comp_with_cinn(self):
        fwd_actual = []
        rev_actual = []
        for place in self.places:
1218 1219
            if not isinstance(place, fluid.CUDAPlace):
                continue
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
            input_ = paddle.to_tensor(
                data=self.x, dtype=self.dtype, place=place, stop_gradient=False
            )
            scale_ = paddle.to_tensor(
                data=self.scale,
                dtype=self.dtype,
                place=place,
                stop_gradient=False,
            )
            bias_ = paddle.to_tensor(
                data=self.bias,
                dtype=self.dtype,
                place=place,
                stop_gradient=False,
            )
            net = PrimNet(
                self.groups,
                self.num_channels,
                scale_,
                bias_,
                self.epsilon,
                self.data_format,
            )
            # failed in cinn test
1244
            net = apply_to_static(net, True)
1245 1246 1247 1248 1249
            output = net(input_)
            grad = paddle.grad(output, input_)
            fwd_actual.append(output.numpy())
            rev_actual.append(grad[0].numpy())

1250 1251 1252 1253
        i = 0
        for place in self.places:
            if not isinstance(place, fluid.CUDAPlace):
                continue
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
            atol = self.threshold_list[i][2]
            rtol = self.threshold_list[i][2]
            np.testing.assert_allclose(
                self.fwd_desire[i],
                fwd_actual[i],
                rtol=rtol,  # mean of uniform distribution, scale for avoid random failed
                atol=atol,
                err_msg='%s jit_cinn fwd' % self.places[i],
            )
            # TODO: fix the diff between cpu and gpu grad is large in original op
            # now use larger threshold when testing cpu grads to bypass cpu grad test
            if self.special_threshold is not None:
                atol = self.special_threshold[i]
                rtol = self.special_threshold[i]
            np.testing.assert_allclose(
                self.rev_desire[i],
                rev_actual[i],
                rtol=rtol,  # mean of uniform distribution, scale for avoid random failed
                atol=atol,
                err_msg='%s jit_cinn rev' % self.places[i],
            )
1275
            i += 1
1276 1277


D
Dun 已提交
1278 1279
if __name__ == '__main__':
    unittest.main()