test_pass_base_list.py 3.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 22 23 24
# 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 random
import sys
import unittest

import numpy as np
from get_gpt_model import FakeDataset, generate_model

import paddle
from paddle.distributed.fleet import auto

T
tianshuo78520a 已提交
25
sys.path.append("../../python/paddle/fluid/tests/unittests")
26 27 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
from test_sparse_addmm_op import get_cuda_version


def apply_pass(use_fused_passes=False, fused_passes_list=[]):
    strategy = auto.Strategy()
    strategy.auto_mode = "semi"
    strategy.reinit = True
    fused_passes = strategy.fused_passes
    fused_passes.enable = use_fused_passes
    fused_passes.fused_passes_list = fused_passes_list
    return strategy


def reset_prog():
    paddle.fluid.framework.switch_main_program(paddle.static.Program())
    paddle.fluid.framework.switch_startup_program(paddle.static.Program())


class TestFusedPassBaseList(unittest.TestCase):
    def setUp(self):
        self.rtol = 1e-5
        self.atol = 1e-8
        self.batch_size = 1
        self.batch_num = 1
        self.clip_norm = 0.2
        self.dataset = FakeDataset(self.batch_size * self.batch_num)

    def init(self, engine):
        paddle.seed(2021)
        np.random.seed(2021)
        random.seed(2021)
57
        place = paddle.fluid.CUDAPlace(paddle.distributed.ParallelEnv().dev_id)
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
        engine._executor = paddle.static.Executor(place)

    def get_engine(self, use_fused_passes=False, fused_passes_list=[]):
        reset_prog()

        strategy = apply_pass(use_fused_passes, fused_passes_list)
        clip = paddle.nn.ClipGradByGlobalNorm(self.clip_norm)
        opt = paddle.optimizer.AdamW(learning_rate=0.00001, grad_clip=clip)
        model, loss = generate_model("serial")

        engine = auto.Engine(model, loss, opt, strategy=strategy)
        self.init(engine)
        return engine

    def check_results(self, ref_losses, check_losses, rtol=None, atol=None):
        np.testing.assert_allclose(
            ref_losses,
            check_losses,
            rtol=rtol or self.rtol,
            atol=atol or self.atol,
            err_msg='pass {} has wrong results!, \nu={}\nv={}\ndiff={}'.format(
                __class__, ref_losses, check_losses, ref_losses - check_losses
            ),
        )

    def test_passes(self):
        losses = []
        if get_cuda_version() >= 11060:
            for use_fused_passes in [True, False]:
                engine = self.get_engine(
                    use_fused_passes,
                    [
                        "fuse_bn_act",
                        "fused_attention",
92
                        "fused_feedforward",
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
                        "fuse_optimizer",
                        "fuse_gemm_epilogue",
                        "fuse_bn_add_act",
                        "fuse_relu_depthwise_conv",
                    ],
                )
                history = engine.fit(
                    self.dataset, 3, batch_size=self.batch_size
                )
                losses.append(np.array(history.history["loss"]))
            self.check_results(losses[0], losses[1])


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