train.py 13.1 KB
Newer Older
T
tianxin04 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2019 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.
"""ERNIE pretraining."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
C
chenxuyi 已提交
18 19
from __future__ import unicode_literals
from __future__ import absolute_import
T
tianxin04 已提交
20 21 22 23

import os
import time
import multiprocessing
C
chenxuyi 已提交
24
import logging
T
tianxin04 已提交
25

26
import numpy as np
T
tianxin04 已提交
27 28 29
import paddle.fluid as fluid

from reader.pretraining import ErnieDataReader
T
tianxin 已提交
30
from model.ernie_v1 import ErnieModel, ErnieConfig
T
tianxin04 已提交
31
from optimization import optimization
C
chenxuyi 已提交
32
from utils.args import print_arguments, check_cuda, prepare_logger
T
tianxin04 已提交
33 34 35 36
from utils.init import init_checkpoint, init_pretraining_params

from pretrain_args import parser

C
chenxuyi 已提交
37
log = logging.getLogger()
T
tianxin04 已提交
38
args = parser.parse_args()
T
format  
tianxin04 已提交
39

T
tianxin04 已提交
40 41
# yapf: enable.

T
format  
tianxin04 已提交
42

T
tianxin04 已提交
43
def create_model(pyreader_name, ernie_config):
44 45 46 47 48 49 50 51 52 53 54
    src_ids = fluid.layers.data(name='1', shape=[-1, args.max_seq_len, 1], dtype='int64')
    pos_ids = fluid.layers.data(name='2', shape=[-1, args.max_seq_len, 1], dtype='int64')
    sent_ids= fluid.layers.data(name='3', shape=[-1, args.max_seq_len, 1], dtype='int64')
    input_mask = fluid.layers.data(name='4', shape=[-1, args.max_seq_len, 1], dtype='float32')
    mask_label = fluid.layers.data(name='5', shape=[-1, 1], dtype='int64')
    mask_pos = fluid.layers.data(name='6', shape=[-1, 1], dtype='int64')
    labels = fluid.layers.data(name='r', shape=[-1, 1], dtype='int64')

    pyreader = fluid.io.DataLoader.from_generator(feed_list=[
        src_ids, pos_ids, sent_ids, input_mask, mask_label, mask_pos, labels
        ], capacity=70, iterable=False)
T
tianxin04 已提交
55 56 57 58 59

    ernie = ErnieModel(
        src_ids=src_ids,
        position_ids=pos_ids,
        sentence_ids=sent_ids,
Y
Yibing Liu 已提交
60
        input_mask=input_mask,
T
tianxin04 已提交
61 62 63 64 65
        config=ernie_config,
        weight_sharing=args.weight_sharing,
        use_fp16=args.use_fp16)

    next_sent_acc, mask_lm_loss, total_loss = ernie.get_pretraining_output(
Y
Yibing Liu 已提交
66
        mask_label, mask_pos, labels)
T
tianxin04 已提交
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

    return pyreader, next_sent_acc, mask_lm_loss, total_loss


def predict_wrapper(args,
                    exe,
                    ernie_config,
                    test_prog=None,
                    pyreader=None,
                    fetch_list=None):
    # Context to do validation.
    filelist = args.test_filelist if args.do_test else args.valid_filelist
    data_reader = ErnieDataReader(
        filelist,
        vocab_path=args.vocab_path,
        batch_size=args.batch_size,
        voc_size=ernie_config['vocab_size'],
        shuffle_files=False,
        epoch=1,
        max_seq_len=args.max_seq_len,
        is_test=True)

    if args.do_test:
        assert args.init_checkpoint is not None, "[FATAL] Please use --init_checkpoint '/path/to/checkpoints' \
                                                  to specify you pretrained model checkpoints"

        init_pretraining_params(exe, args.init_checkpoint, test_prog)

    def predict(exe=exe, pyreader=pyreader):

97
        pyreader.set_batch_generator(data_reader.data_generator())
T
tianxin04 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        pyreader.start()

        cost = 0
        lm_cost = 0
        acc = 0
        steps = 0
        time_begin = time.time()
        while True:
            try:
                each_next_acc, each_mask_lm_cost, each_total_cost = exe.run(
                    fetch_list=fetch_list, program=test_prog)
                acc += each_next_acc
                lm_cost += each_mask_lm_cost
                cost += each_total_cost
                steps += 1
                if args.do_test and steps % args.skip_steps == 0:
C
chenxuyi 已提交
114
                    log.info("[test_set] steps: %d" % steps)
T
tianxin04 已提交
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

            except fluid.core.EOFException:
                pyreader.reset()
                break

        used_time = time.time() - time_begin
        return cost, lm_cost, acc, steps, (args.skip_steps / used_time)

    return predict


def test(args):
    ernie_config = ErnieConfig(args.ernie_config_path)
    ernie_config.print_config()

    test_prog = fluid.Program()
    test_startup = fluid.Program()
    with fluid.program_guard(test_prog, test_startup):
        with fluid.unique_name.guard():
            test_pyreader, next_sent_acc, mask_lm_loss, total_loss = create_model(
                pyreader_name='test_reader', ernie_config=ernie_config)

    test_prog = test_prog.clone(for_test=True)

    place = fluid.CUDAPlace(0) if args.use_cuda == True else fluid.CPUPlace()
    exe = fluid.Executor(place)
    exe.run(test_startup)

    predict = predict_wrapper(
        args,
        exe,
        ernie_config,
        test_prog=test_prog,
        pyreader=test_pyreader,
        fetch_list=[next_sent_acc.name, mask_lm_loss.name, total_loss.name])

C
chenxuyi 已提交
151
    log.info("test begin")
T
tianxin04 已提交
152
    loss, lm_loss, acc, steps, speed = predict()
C
chenxuyi 已提交
153
    log.info(
T
tianxin04 已提交
154 155 156 157 158 159 160
        "[test_set] loss: %f, global ppl: %f, next_sent_acc: %f, speed: %f steps/s"
        % (np.mean(np.array(loss) / steps),
           np.exp(np.mean(np.array(lm_loss) / steps)),
           np.mean(np.array(acc) / steps), speed))


def train(args):
C
chenxuyi 已提交
161
    log.info("pretraining start")
T
tianxin04 已提交
162 163 164 165 166 167 168 169 170
    ernie_config = ErnieConfig(args.ernie_config_path)
    ernie_config.print_config()

    train_program = fluid.Program()
    startup_prog = fluid.Program()
    with fluid.program_guard(train_program, startup_prog):
        with fluid.unique_name.guard():
            train_pyreader, next_sent_acc, mask_lm_loss, total_loss = create_model(
                pyreader_name='train_reader', ernie_config=ernie_config)
C
chenxuyi 已提交
171
            scheduled_lr, _ = optimization(
T
tianxin04 已提交
172 173 174 175 176 177 178 179
                loss=total_loss,
                warmup_steps=args.warmup_steps,
                num_train_steps=args.num_train_steps,
                learning_rate=args.learning_rate,
                train_program=train_program,
                startup_prog=startup_prog,
                weight_decay=args.weight_decay,
                scheduler=args.lr_scheduler,
C
chenxuyi 已提交
180 181 182 183 184 185 186 187
                use_fp16=args.use_fp16,
                use_dynamic_loss_scaling=args.use_dynamic_loss_scaling,
                init_loss_scaling=args.init_loss_scaling,
                incr_every_n_steps=args.incr_every_n_steps,
                decr_every_n_nan_or_inf=args.decr_every_n_nan_or_inf,
                incr_ratio=args.incr_ratio,
                decr_ratio=args.decr_ratio)

T
tianxin04 已提交
188 189 190 191 192 193 194 195 196

    test_prog = fluid.Program()
    with fluid.program_guard(test_prog, startup_prog):
        with fluid.unique_name.guard():
            test_pyreader, next_sent_acc, mask_lm_loss, total_loss = create_model(
                pyreader_name='test_reader', ernie_config=ernie_config)

    test_prog = test_prog.clone(for_test=True)

C
chenxuyi 已提交
197 198 199
    if len(fluid.cuda_places()) == 0:
        raise RuntimeError('not cuda device cound, check ur env setting')

T
tianxin04 已提交
200
    if args.use_cuda:
C
chenxuyi 已提交
201
        place = fluid.cuda_places()[0]
T
tianxin04 已提交
202 203 204 205 206
        dev_count = fluid.core.get_cuda_device_count()
    else:
        place = fluid.CPUPlace()
        dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))

C
chenxuyi 已提交
207 208 209
    log.info("Device count %d" % dev_count)
    log.info("theoretical memory usage: ")
    log.info(fluid.contrib.memory_usage(
T
tianxin04 已提交
210 211 212 213
        program=train_program, batch_size=args.batch_size // args.max_seq_len))

    nccl2_num_trainers = 1
    nccl2_trainer_id = 0
C
chenxuyi 已提交
214
    log.info("args.is_distributed: %s" % args.is_distributed)
T
tianxin04 已提交
215
    if args.is_distributed:
C
chenxuyi 已提交
216
        worker_endpoints_env = os.getenv("PADDLE_TRAINER_ENDPOINTS")
T
tianxin04 已提交
217 218
        worker_endpoints = worker_endpoints_env.split(",")
        trainers_num = len(worker_endpoints)
C
chenxuyi 已提交
219
        current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
T
tianxin04 已提交
220 221
        trainer_id = worker_endpoints.index(current_endpoint)
        if trainer_id == 0:
C
chenxuyi 已提交
222
            log.info("train_id == 0, sleep 60s")
T
tianxin04 已提交
223
            time.sleep(60)
C
chenxuyi 已提交
224
        log.info("worker_endpoints:{} trainers_num:{} current_endpoint:{} \
T
format  
tianxin04 已提交
225
              trainer_id:{}".format(worker_endpoints, trainers_num,
T
tianxin04 已提交
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 277 278 279 280 281 282 283 284
                                    current_endpoint, trainer_id))

        # prepare nccl2 env.
        config = fluid.DistributeTranspilerConfig()
        config.mode = "nccl2"
        t = fluid.DistributeTranspiler(config=config)
        t.transpile(
            trainer_id,
            trainers=worker_endpoints_env,
            current_endpoint=current_endpoint,
            program=train_program,
            startup_program=startup_prog)
        nccl2_num_trainers = trainers_num
        nccl2_trainer_id = trainer_id

    exe = fluid.Executor(place)
    exe.run(startup_prog)

    if args.init_checkpoint and args.init_checkpoint != "":
        init_checkpoint(exe, args.init_checkpoint, train_program, args.use_fp16)

    data_reader = ErnieDataReader(
        filelist=args.train_filelist,
        batch_size=args.batch_size,
        vocab_path=args.vocab_path,
        voc_size=ernie_config['vocab_size'],
        epoch=args.epoch,
        max_seq_len=args.max_seq_len,
        generate_neg_sample=args.generate_neg_sample)

    exec_strategy = fluid.ExecutionStrategy()
    if args.use_fast_executor:
        exec_strategy.use_experimental_executor = True
    exec_strategy.num_threads = dev_count
    exec_strategy.num_iteration_per_drop_scope = min(10, args.skip_steps)

    build_strategy = fluid.BuildStrategy()
    build_strategy.remove_unnecessary_lock = False

    train_exe = fluid.ParallelExecutor(
        use_cuda=args.use_cuda,
        loss_name=total_loss.name,
        build_strategy=build_strategy,
        exec_strategy=exec_strategy,
        main_program=train_program,
        num_trainers=nccl2_num_trainers,
        trainer_id=nccl2_trainer_id)

    if args.valid_filelist and args.valid_filelist != "":
        predict = predict_wrapper(
            args,
            exe,
            ernie_config,
            test_prog=test_prog,
            pyreader=test_pyreader,
            fetch_list=[
                next_sent_acc.name, mask_lm_loss.name, total_loss.name
            ])

285
    train_pyreader.set_batch_generator(data_reader.data_generator())
T
tianxin04 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    train_pyreader.start()
    steps = 0
    cost = []
    lm_cost = []
    acc = []
    time_begin = time.time()
    while steps < args.num_train_steps:
        try:
            steps += nccl2_num_trainers
            skip_steps = args.skip_steps * nccl2_num_trainers

            if nccl2_trainer_id != 0:
                train_exe.run(fetch_list=[])
                continue

            if steps % skip_steps != 0:
                train_exe.run(fetch_list=[])
            else:
                each_next_acc, each_mask_lm_cost, each_total_cost, np_lr = train_exe.run(
                    fetch_list=[
                        next_sent_acc.name, mask_lm_loss.name, total_loss.name,
                        scheduled_lr.name
                    ])
                acc.extend(each_next_acc)
                lm_cost.extend(each_mask_lm_cost)
                cost.extend(each_total_cost)

C
chenxuyi 已提交
313
                log.info("feed_queue size %d" % train_pyreader.queue.size())
T
tianxin04 已提交
314 315 316 317
                time_end = time.time()
                used_time = time_end - time_begin
                epoch, current_file_index, total_file, current_file, mask_type = data_reader.get_progress(
                )
C
chenxuyi 已提交
318 319
                log.info("current learning_rate:%f" % np_lr[0])
                log.info(
T
format  
tianxin04 已提交
320 321 322 323 324 325 326
                    "epoch: %d, progress: %d/%d, step: %d, loss: %f, "
                    "ppl: %f, next_sent_acc: %f, speed: %f steps/s, file: %s, mask_type: %s"
                    % (epoch, current_file_index, total_file, steps,
                       np.mean(np.array(cost)),
                       np.mean(np.exp(np.array(lm_cost))),
                       np.mean(np.array(acc)), skip_steps / used_time,
                       current_file, mask_type))
T
tianxin04 已提交
327 328 329 330 331 332 333 334 335 336 337 338
                cost = []
                lm_cost = []
                acc = []
                time_begin = time.time()

            if steps % args.save_steps == 0:
                save_path = os.path.join(args.checkpoints, "step_" + str(steps))
                fluid.io.save_persistables(exe, save_path, train_program)

            if args.valid_filelist and steps % args.validation_steps == 0:
                vali_cost, vali_lm_cost, vali_acc, vali_steps, vali_speed = predict(
                )
C
chenxuyi 已提交
339
                log.info("[validation_set] epoch: %d, step: %d, "
T
tianxin04 已提交
340 341
                      "loss: %f, global ppl: %f, batch-averged ppl: %f, "
                      "next_sent_acc: %f, speed: %f steps/s" %
T
format  
tianxin04 已提交
342
                      (epoch, steps, np.mean(np.array(vali_cost) / vali_steps),
T
tianxin04 已提交
343 344 345 346 347 348 349 350 351 352
                       np.exp(np.mean(np.array(vali_lm_cost) / vali_steps)),
                       np.mean(np.exp(np.array(vali_lm_cost) / vali_steps)),
                       np.mean(np.array(vali_acc) / vali_steps), vali_speed))

        except fluid.core.EOFException:
            train_pyreader.reset()
            break


if __name__ == '__main__':
C
chenxuyi 已提交
353
    prepare_logger(log)
T
tianxin04 已提交
354
    print_arguments(args)
T
tianxin 已提交
355
    check_cuda(args.use_cuda)
T
tianxin04 已提交
356 357 358 359
    if args.do_test:
        test(args)
    else:
        train(args)