test_bert_prim_cinn.py 5.2 KB
Newer Older
W
WangZhen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (c) 2023 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 os
import time
import unittest

import numpy as np
from bert import Bert, BertPretrainingCriterion, create_pretraining_dataset

import paddle
23
from paddle import fluid
W
WangZhen 已提交
24
from paddle.dataset.common import DATA_HOME, download
25
from paddle.fluid import core
W
WangZhen 已提交
26 27 28 29 30 31 32 33 34

SEED = 2023
BATCH_SIZE = 2

URL = 'https://paddle-ci.gz.bcebos.com/prim_cinn/bert_training_data.npz'
MODULE_NAME = 'test_bert_prim_cinn'
MD5SUM = '71e730ee8d7aa77a215b7e898aa089af'
SAVE_NAME = 'bert_training_data.npz'

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

DY2ST_PRIM_GT = [
    11.144556999206543,
    10.343620300292969,
    10.330279350280762,
    10.276118278503418,
    10.222086906433105,
    10.194628715515137,
    10.14902114868164,
    10.096250534057617,
    10.104615211486816,
    9.985644340515137,
]
DY2ST_CINN_GT = [
    10.649632453918457,
    10.333406448364258,
    10.33541202545166,
    10.260543823242188,
    10.219606399536133,
    10.176884651184082,
    10.124699592590332,
    10.072620391845703,
    10.112163543701172,
    9.969393730163574,
]
DY2ST_PRIM_CINN_GT = [
    11.144556999206543,
    10.343620300292969,
    10.330279350280762,
    10.276118278503418,
    10.222086906433105,
    10.194628715515137,
    10.149020195007324,
    10.096250534057617,
    10.104615211486816,
    9.985644340515137,
]

W
WangZhen 已提交
73 74 75 76 77 78 79 80 81
if core.is_compiled_with_cuda():
    paddle.set_flags({'FLAGS_cudnn_deterministic': True})


def train(to_static, enable_prim, enable_cinn):
    if core.is_compiled_with_cuda():
        paddle.set_device('gpu')
    else:
        paddle.set_device('cpu')
82
    fluid.core._set_prim_all_enabled(enable_prim)
W
WangZhen 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95

    np.random.seed(SEED)
    paddle.seed(SEED)
    # paddle.framework.random._manual_program_seed(SEED)

    train_data_loader = create_pretraining_dataset(
        os.path.join(DATA_HOME, MODULE_NAME, SAVE_NAME),
        20,
        {},
        batch_size=BATCH_SIZE,
        worker_init=None,
    )

96 97
    # Now only apply dy2st for encoder
    bert = Bert(to_static, enable_cinn)
W
WangZhen 已提交
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
    criterion = BertPretrainingCriterion()

    optimizer = fluid.optimizer.Adam(parameter_list=bert.parameters())

    losses = []
    for step, batch in enumerate(train_data_loader):
        start_time = time.time()
        (
            input_ids,
            segment_ids,
            input_mask,
            masked_lm_positions,
            masked_lm_labels,
            next_sentence_labels,
            masked_lm_scale,
        ) = batch

        prediction_scores, seq_relationship_score = bert(
            input_ids=input_ids,
            token_type_ids=segment_ids,
            attention_mask=input_mask,
            masked_positions=masked_lm_positions,
        )

        loss = criterion(
            prediction_scores,
            seq_relationship_score,
            masked_lm_labels,
            next_sentence_labels,
            masked_lm_scale,
        )

        loss.backward()
        optimizer.minimize(loss)
        bert.clear_gradients()
133
        losses.append(loss.numpy().item())
W
WangZhen 已提交
134 135 136 137 138 139 140 141 142 143

        print(
            "step: {}, loss: {}, batch_cost: {:.5}".format(
                step,
                loss.numpy(),
                time.time() - start_time,
            )
        )
        if step >= 9:
            break
144
    print(losses)
W
WangZhen 已提交
145 146 147 148 149 150 151 152
    return losses


class TestBert(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        download(URL, MODULE_NAME, MD5SUM, SAVE_NAME)

153 154 155 156 157 158 159
    def tearDown(self):
        paddle.set_flags({'FLAGS_deny_cinn_ops': ''})

    @unittest.skipIf(
        not (paddle.is_compiled_with_cinn() and paddle.is_compiled_with_cuda()),
        "paddle is not compiled with CINN and CUDA",
    )
W
WangZhen 已提交
160 161
    def test_prim(self):
        dy2st_prim = train(to_static=True, enable_prim=True, enable_cinn=False)
162
        np.testing.assert_allclose(dy2st_prim, DY2ST_PRIM_GT, rtol=1e-5)
W
WangZhen 已提交
163 164

    @unittest.skipIf(
165 166
        not (paddle.is_compiled_with_cinn() and paddle.is_compiled_with_cuda()),
        "paddle is not compiled with CINN and CUDA",
W
WangZhen 已提交
167 168
    )
    def test_cinn(self):
169
        paddle.set_flags({'FLAGS_deny_cinn_ops': "dropout"})
W
WangZhen 已提交
170
        dy2st_cinn = train(to_static=True, enable_prim=False, enable_cinn=True)
171
        np.testing.assert_allclose(dy2st_cinn, DY2ST_CINN_GT, rtol=1e-5)
W
WangZhen 已提交
172 173

    @unittest.skipIf(
174 175
        not (paddle.is_compiled_with_cinn() and paddle.is_compiled_with_cuda()),
        "paddle is not compiled with CINN and CUDA",
W
WangZhen 已提交
176 177
    )
    def test_prim_cinn(self):
178 179 180
        paddle.set_flags(
            {'FLAGS_deny_cinn_ops': "gaussian_random;uniform_random"}
        )
W
WangZhen 已提交
181 182 183
        dy2st_prim_cinn = train(
            to_static=True, enable_prim=True, enable_cinn=True
        )
184 185 186
        np.testing.assert_allclose(
            dy2st_prim_cinn, DY2ST_PRIM_CINN_GT, rtol=1e-5
        )
W
WangZhen 已提交
187 188 189 190


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