run_classifier.py 16.6 KB
Newer Older
T
tianxin04 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   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.
"""Finetuning on classification tasks."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
C
chenxuyi 已提交
19 20
from __future__ import unicode_literals
from __future__ import absolute_import
T
tianxin04 已提交
21 22 23

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

T
tianxin 已提交
27 28 29 30 31
# NOTE(paddle-dev): All of these flags should be
# set before `import paddle`. Otherwise, it would
# not take any effect.
os.environ['FLAGS_eager_delete_tensor_gb'] = '0'  # enable gc

T
tianxin04 已提交
32 33 34 35
import paddle.fluid as fluid

import reader.task_reader as task_reader
from model.ernie import ErnieConfig
T
tianxin 已提交
36
from finetune.classifier import create_model, evaluate, predict
T
tianxin04 已提交
37
from optimization import optimization
C
chenxuyi 已提交
38
from utils.args import print_arguments, check_cuda, prepare_logger
T
tianxin04 已提交
39
from utils.init import init_pretraining_params, init_checkpoint
Z
zhengya01 已提交
40
from utils.cards import get_cards
T
format  
tianxin04 已提交
41
from finetune_args import parser
T
tianxin04 已提交
42 43

args = parser.parse_args()
C
chenxuyi 已提交
44
log = logging.getLogger()
T
tianxin04 已提交
45

T
format  
tianxin04 已提交
46

T
tianxin04 已提交
47 48 49 50 51
def main(args):
    ernie_config = ErnieConfig(args.ernie_config_path)
    ernie_config.print_config()

    if args.use_cuda:
C
chenxuyi 已提交
52 53 54
        dev_list = fluid.cuda_places()
        place = dev_list[0]
        dev_count = len(dev_list)
T
tianxin04 已提交
55 56 57 58 59
    else:
        place = fluid.CPUPlace()
        dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))
    exe = fluid.Executor(place)

T
format  
tianxin04 已提交
60 61 62 63 64 65
    reader = task_reader.ClassifyReader(
        vocab_path=args.vocab_path,
        label_map_config=args.label_map_config,
        max_seq_len=args.max_seq_len,
        do_lower_case=args.do_lower_case,
        in_tokens=args.in_tokens,
T
tianxin 已提交
66 67 68 69 70 71
        random_seed=args.random_seed,
        tokenizer=args.tokenizer,
        is_classify=args.is_classify,
        is_regression=args.is_regression,
        for_cn=args.for_cn,
        task_id=args.task_id)
T
tianxin04 已提交
72 73 74 75 76

    if not (args.do_train or args.do_val or args.do_test):
        raise ValueError("For args `do_train`, `do_val` and `do_test`, at "
                         "least one of them must be True.")

T
tianxin 已提交
77 78
    if args.do_test:
        assert args.test_save is not None
T
tianxin04 已提交
79 80 81 82 83 84 85 86 87
    startup_prog = fluid.Program()
    if args.random_seed is not None:
        startup_prog.random_seed = args.random_seed

    if args.do_train:
        train_data_generator = reader.data_generator(
            input_file=args.train_set,
            batch_size=args.batch_size,
            epoch=args.epoch,
T
tianxin 已提交
88 89
            dev_count=dev_count,
            shuffle=True,
T
tianxin04 已提交
90 91 92 93 94 95 96 97 98 99 100
            phase="train")

        num_train_examples = reader.get_num_examples(args.train_set)

        if args.in_tokens:
            max_train_steps = args.epoch * num_train_examples // (
                args.batch_size // args.max_seq_len) // dev_count
        else:
            max_train_steps = args.epoch * num_train_examples // args.batch_size // dev_count

        warmup_steps = int(max_train_steps * args.warmup_proportion)
C
chenxuyi 已提交
101 102 103 104
        log.info("Device count: %d" % dev_count)
        log.info("Num train examples: %d" % num_train_examples)
        log.info("Max train steps: %d" % max_train_steps)
        log.info("Num warmup steps: %d" % warmup_steps)
T
tianxin04 已提交
105 106

        train_program = fluid.Program()
Z
zhengya01 已提交
107 108
        if args.random_seed is not None and args.enable_ce:
            train_program.random_seed = args.random_seed
T
tianxin04 已提交
109 110 111 112 113 114

        with fluid.program_guard(train_program, startup_prog):
            with fluid.unique_name.guard():
                train_pyreader, graph_vars = create_model(
                    args,
                    pyreader_name='train_reader',
T
tianxin 已提交
115 116 117 118
                    ernie_config=ernie_config,
                    is_classify=args.is_classify,
                    is_regression=args.is_regression)
                scheduled_lr, loss_scaling = optimization(
T
tianxin04 已提交
119 120 121 122 123 124 125 126
                    loss=graph_vars["loss"],
                    warmup_steps=warmup_steps,
                    num_train_steps=max_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 已提交
127 128 129 130 131 132 133
		    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 已提交
134 135 136 137 138 139 140 141 142

        if args.verbose:
            if args.in_tokens:
                lower_mem, upper_mem, unit = fluid.contrib.memory_usage(
                    program=train_program,
                    batch_size=args.batch_size // args.max_seq_len)
            else:
                lower_mem, upper_mem, unit = fluid.contrib.memory_usage(
                    program=train_program, batch_size=args.batch_size)
C
chenxuyi 已提交
143
            log.info("Theoretical memory usage in training: %.3f - %.3f %s" %
T
tianxin04 已提交
144 145 146 147 148 149 150 151 152
                  (lower_mem, upper_mem, unit))

    if args.do_val or args.do_test:
        test_prog = fluid.Program()
        with fluid.program_guard(test_prog, startup_prog):
            with fluid.unique_name.guard():
                test_pyreader, graph_vars = create_model(
                    args,
                    pyreader_name='test_reader',
T
tianxin 已提交
153 154 155
                    ernie_config=ernie_config,
                    is_classify=args.is_classify,
                    is_regression=args.is_regression)
T
tianxin04 已提交
156 157

        test_prog = test_prog.clone(for_test=True)
T
tianxin 已提交
158 159
    nccl2_num_trainers = 1
    nccl2_trainer_id = 0
C
chenxuyi 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    if args.is_distributed:
        trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
        worker_endpoints_env = os.getenv("PADDLE_TRAINER_ENDPOINTS")
        current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
        worker_endpoints = worker_endpoints_env.split(",")
        trainers_num = len(worker_endpoints)
        
        log.info("worker_endpoints:{} trainers_num:{} current_endpoint:{} \
              trainer_id:{}".format(worker_endpoints, trainers_num,
                                    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 if args.do_train else test_prog,
            startup_program=startup_prog)
        nccl2_num_trainers = trainers_num
        nccl2_trainer_id = trainer_id

    exe = fluid.Executor(place)
T
tianxin04 已提交
185 186 187 188
    exe.run(startup_prog)

    if args.do_train:
        if args.init_checkpoint and args.init_pretraining_params:
C
chenxuyi 已提交
189
            log.warning(
T
tianxin04 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                "WARNING: args 'init_checkpoint' and 'init_pretraining_params' "
                "both are set! Only arg 'init_checkpoint' is made valid.")
        if args.init_checkpoint:
            init_checkpoint(
                exe,
                args.init_checkpoint,
                main_program=startup_prog,
                use_fp16=args.use_fp16)
        elif args.init_pretraining_params:
            init_pretraining_params(
                exe,
                args.init_pretraining_params,
                main_program=startup_prog,
                use_fp16=args.use_fp16)
    elif args.do_val or args.do_test:
        if not args.init_checkpoint:
            raise ValueError("args 'init_checkpoint' should be set if"
                             "only doing validation or testing!")
        init_checkpoint(
            exe,
            args.init_checkpoint,
            main_program=startup_prog,
            use_fp16=args.use_fp16)

    if args.do_train:
        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 = args.num_iteration_per_drop_scope

        train_exe = fluid.ParallelExecutor(
            use_cuda=args.use_cuda,
            loss_name=graph_vars["loss"].name,
            exec_strategy=exec_strategy,
T
tianxin 已提交
225 226 227
            main_program=train_program,
            num_trainers=nccl2_num_trainers,
            trainer_id=nccl2_trainer_id)
T
tianxin04 已提交
228 229 230 231 232

        train_pyreader.decorate_tensor_provider(train_data_generator)
    else:
        train_exe = None

T
tianxin 已提交
233 234 235 236 237 238 239 240
    test_exe = exe
    if args.do_val or args.do_test:
        if args.use_multi_gpu_test:
            test_exe = fluid.ParallelExecutor(
                use_cuda=args.use_cuda,
                main_program=test_prog,
                share_vars_from=train_exe)

T
tianxin04 已提交
241 242 243 244 245 246
    if args.do_train:
        train_pyreader.start()
        steps = 0
        if warmup_steps > 0:
            graph_vars["learning_rate"] = scheduled_lr

Z
zhengya01 已提交
247
        ce_info = []
T
tianxin04 已提交
248
        time_begin = time.time()
T
tianxin 已提交
249 250
        last_epoch = 0
        current_epoch = 0
T
tianxin04 已提交
251 252 253 254 255 256
        while True:
            try:
                steps += 1
                if steps % args.skip_steps != 0:
                    train_exe.run(fetch_list=[])
                else:
T
tianxin 已提交
257 258 259 260 261 262 263 264 265
                    outputs = evaluate(
                        train_exe,
                        train_program,
                        train_pyreader,
                        graph_vars,
                        "train",
                        metric=args.metric,
                        is_classify=args.is_classify,
                        is_regression=args.is_regression)
T
tianxin04 已提交
266 267 268 269 270 271 272

                    if args.verbose:
                        verbose = "train pyreader queue size: %d, " % train_pyreader.queue.size(
                        )
                        verbose += "learning rate: %f" % (
                            outputs["learning_rate"]
                            if warmup_steps > 0 else args.learning_rate)
C
chenxuyi 已提交
273
                        log.info(verbose)
T
tianxin04 已提交
274 275 276 277

                    current_example, current_epoch = reader.get_train_progress()
                    time_end = time.time()
                    used_time = time_end - time_begin
T
tianxin 已提交
278 279

                    if args.is_classify:
C
chenxuyi 已提交
280
                        log.info(
T
tianxin 已提交
281 282 283 284 285 286 287 288
                            "epoch: %d, progress: %d/%d, step: %d, ave loss: %f, "
                            "ave acc: %f, speed: %f steps/s" %
                            (current_epoch, current_example, num_train_examples,
                             steps, outputs["loss"], outputs["accuracy"],
                             args.skip_steps / used_time))
                        ce_info.append(
                            [outputs["loss"], outputs["accuracy"], used_time])
                    if args.is_regression:
C
chenxuyi 已提交
289
                        log.info(
T
tianxin 已提交
290 291 292 293 294
                            "epoch: %d, progress: %d/%d, step: %d, ave loss: %f, "
                            " speed: %f steps/s" %
                            (current_epoch, current_example, num_train_examples,
                             steps, outputs["loss"],
                             args.skip_steps / used_time))
T
tianxin04 已提交
295 296
                    time_begin = time.time()

C
chenxuyi 已提交
297 298 299 300 301
                if nccl2_trainer_id == 0:
                    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)
T
tianxin04 已提交
302

C
chenxuyi 已提交
303 304 305 306 307 308
                    if steps % args.validation_steps == 0 or last_epoch != current_epoch:
                        # evaluate dev set
                        if args.do_val:
                            evaluate_wrapper(args, reader, exe, test_prog,
                                             test_pyreader, graph_vars,
                                             current_epoch, steps)
T
tianxin 已提交
309

C
chenxuyi 已提交
310 311 312 313
                        if args.do_test:
                            predict_wrapper(args, reader, exe, test_prog,
                                            test_pyreader, graph_vars,
                                            current_epoch, steps)
T
tianxin 已提交
314 315 316 317

                if last_epoch != current_epoch:
                    last_epoch = current_epoch

T
tianxin04 已提交
318 319 320 321 322
            except fluid.core.EOFException:
                save_path = os.path.join(args.checkpoints, "step_" + str(steps))
                fluid.io.save_persistables(exe, save_path, train_program)
                train_pyreader.reset()
                break
Z
zhengya01 已提交
323 324 325 326 327 328 329 330 331 332
        if args.enable_ce:
            card_num = get_cards()
            ce_loss = 0
            ce_acc = 0
            ce_time = 0
            try:
                ce_loss = ce_info[-2][0]
                ce_acc = ce_info[-2][1]
                ce_time = ce_info[-2][2]
            except:
C
chenxuyi 已提交
333 334 335 336
                log.info("ce info error")
            log.info("kpis\ttrain_duration_card%s\t%s" % (card_num, ce_time))
            log.info("kpis\ttrain_loss_card%s\t%f" % (card_num, ce_loss))
            log.info("kpis\ttrain_acc_card%s\t%f" % (card_num, ce_acc))
T
tianxin04 已提交
337 338 339

    # final eval on dev set
    if args.do_val:
T
tianxin 已提交
340 341 342 343 344 345 346 347 348 349
        evaluate_wrapper(args, reader, exe, test_prog, test_pyreader,
                         graph_vars, current_epoch, steps)

    # final eval on test set
    if args.do_test:
        predict_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars,
                        current_epoch, steps)

    # final eval on dianostic, hack for glue-ax
    if args.diagnostic:
T
tianxin04 已提交
350 351
        test_pyreader.decorate_tensor_provider(
            reader.data_generator(
T
tianxin 已提交
352
                args.diagnostic,
T
format  
tianxin04 已提交
353 354
                batch_size=args.batch_size,
                epoch=1,
T
tianxin 已提交
355
                dev_count=1,
T
tianxin04 已提交
356 357
                shuffle=False))

C
chenxuyi 已提交
358
        log.info("Final diagnostic")
T
tianxin 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371
        qids, preds, probs = predict(
            test_exe,
            test_prog,
            test_pyreader,
            graph_vars,
            is_classify=args.is_classify,
            is_regression=args.is_regression)
        assert len(qids) == len(preds), '{} v.s. {}'.format(
            len(qids), len(preds))
        with open(args.diagnostic_save, 'w') as f:
            for id, s, p in zip(qids, preds, probs):
                f.write('{}\t{}\t{}\n'.format(id, s, p))

C
chenxuyi 已提交
372
        log.info("Done final diagnostic, saving to {}".format(
T
tianxin 已提交
373 374 375 376 377 378 379
            args.diagnostic_save))


def evaluate_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars,
                     epoch, steps):
    # evaluate dev set
    for ds in args.dev_set.split(','):
T
tianxin04 已提交
380 381
        test_pyreader.decorate_tensor_provider(
            reader.data_generator(
T
tianxin 已提交
382 383 384 385 386
                ds,
                batch_size=args.predict_batch_size,
                epoch=1,
                dev_count=1,
                shuffle=False))
C
chenxuyi 已提交
387
        log.info("validation result of dataset {}:".format(ds))
T
tianxin 已提交
388 389 390 391 392 393 394 395 396
        evaluate_info = evaluate(
            exe,
            test_prog,
            test_pyreader,
            graph_vars,
            "dev",
            metric=args.metric,
            is_classify=args.is_classify,
            is_regression=args.is_regression)
C
chenxuyi 已提交
397
        log.info(evaluate_info + ', file: {}, epoch: {}, steps: {}'.format(
T
tianxin 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411
            ds, epoch, steps))


def predict_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars,
                    epoch, steps):
    test_sets = args.test_set.split(',')
    save_dirs = args.test_save.split(',')
    assert len(test_sets) == len(save_dirs)

    for test_f, save_f in zip(test_sets, save_dirs):
        test_pyreader.decorate_tensor_provider(
            reader.data_generator(
                test_f,
                batch_size=args.predict_batch_size,
T
tianxin04 已提交
412
                epoch=1,
T
tianxin 已提交
413
                dev_count=1,
T
tianxin04 已提交
414
                shuffle=False))
T
tianxin 已提交
415 416

        save_path = save_f + '.' + str(epoch) + '.' + str(steps)
C
chenxuyi 已提交
417
        log.info("testing {}, save to {}".format(test_f, save_path))
T
tianxin 已提交
418 419 420 421 422 423 424 425 426 427 428
        qids, preds, probs = predict(
            exe,
            test_prog,
            test_pyreader,
            graph_vars,
            is_classify=args.is_classify,
            is_regression=args.is_regression)

        save_dir = os.path.dirname(save_path)
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
C
chenxuyi 已提交
429 430 431
        else:
            log.warning('save dir exsits: %s, will skip saving' % save_dir)

T
tianxin 已提交
432 433 434 435

        with open(save_path, 'w') as f:
            for id, s, p in zip(qids, preds, probs):
                f.write('{}\t{}\t{}\n'.format(id, s, p))
T
tianxin04 已提交
436 437 438


if __name__ == '__main__':
C
chenxuyi 已提交
439
    prepare_logger(log)
T
tianxin04 已提交
440
    print_arguments(args)
T
tianxin 已提交
441
    check_cuda(args.use_cuda)
T
tianxin04 已提交
442
    main(args)