finetune.py 18.2 KB
Newer Older
W
wuzewu 已提交
1
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
Z
Zeyu Chen 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

W
wuzewu 已提交
15 16 17 18
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

Z
Zeyu Chen 已提交
19 20
import os
import time
Z
Zeyu Chen 已提交
21
import multiprocessing
Z
Zeyu Chen 已提交
22

W
wuzewu 已提交
23 24
import paddle
import paddle.fluid as fluid
25
import numpy as np
Z
Zeyu Chen 已提交
26

W
wuzewu 已提交
27 28 29 30 31
from paddlehub.common.logger import logger
from paddlehub.finetune.strategy import BERTFinetuneStrategy, DefaultStrategy
from paddlehub.finetune.checkpoint import load_checkpoint, save_checkpoint
from visualdl import LogWriter
import paddlehub as hub
W
wuzewu 已提交
32

Z
Zeyu Chen 已提交
33

34 35 36 37 38 39 40 41 42 43 44
def _get_running_device_info(config):
    if config.use_cuda:
        place = fluid.CUDAPlace(0)
        dev_count = fluid.core.get_cuda_device_count()
    else:
        place = fluid.CPUPlace()
        dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count()))

    return place, dev_count


45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
def _do_memory_optimization(task, config):
    if config.enable_memory_optim:
        logger.info("Memory optimization start...")
        task_var_name = task.metric_variable_names()
        logger.info(
            "Skip memory optimization on variables: {}".format(task_var_name))
        optimize_time_begin = time.time()
        fluid.memory_optimize(
            input_program=fluid.default_main_program(),
            # skip memory optimization on task metric variables
            skip_opt_set=task_var_name)
        time_used = time.time() - optimize_time_begin
        logger.info("Memory optimization done! Time elapsed %f sec" % time_used)

    lower_mem, upper_mem, unit = fluid.contrib.memory_usage(
        program=fluid.default_main_program(), batch_size=config.batch_size)
61
    logger.info("Theoretical memory usage in training: %.2f - %.2f %s" %
62 63 64
                (lower_mem, upper_mem, unit)),


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 92 93 94 95 96 97 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
def _finetune_seq_label_task(task,
                             data_reader,
                             feed_list,
                             config=None,
                             do_eval=False):
    """
    Finetune sequence labeling task, evaluate metric is F1, precision and recall

    """
    main_program = task.main_program()
    startup_program = task.startup_program()
    loss = task.variable("loss")
    seq_len = task.variable("seq_len")

    num_epoch = config.num_epoch
    batch_size = config.batch_size

    place, dev_count = _get_running_device_info(config)
    with fluid.program_guard(main_program, startup_program):
        exe = fluid.Executor(place=place)
        data_feeder = fluid.DataFeeder(feed_list=feed_list, place=place)

        # Select strategy
        if isinstance(config.strategy, hub.BERTFinetuneStrategy):
            scheduled_lr = config.strategy.execute(loss, main_program,
                                                   data_reader, config)
        elif isinstance(config.strategy, hub.DefaultStrategy):
            config.strategy.execute(loss)
        #TODO: add more finetune strategy

        _do_memory_optimization(task, config)

        # Try to restore model training checkpoint
        current_epoch, global_step = load_checkpoint(config.checkpoint_dir, exe)

        train_time_used = 0
        logger.info("PaddleHub finetune start")

        # Finetune loop
        for epoch in range(current_epoch, num_epoch + 1):
            train_reader = data_reader.data_generator(
                batch_size=batch_size, phase='train')
            num_trained_examples = loss_sum = 0
            for batch in train_reader():
                num_batch_examples = len(batch)
                train_time_begin = time.time()
                loss_v = exe.run(
                    feed=data_feeder.feed(batch), fetch_list=[loss.name])
                train_time_used += time.time() - train_time_begin
                global_step += 1
                num_trained_examples += num_batch_examples
                loss_sum += loss_v[0] * num_batch_examples

                # log fintune status
                if global_step % config.log_interval == 0:
                    avg_loss = loss_sum / num_trained_examples
                    speed = config.log_interval / train_time_used
                    logger.info("step %d: loss=%.5f [step/sec: %.2f]" %
                                (global_step, avg_loss, speed))

                    train_time_used = 0
                    num_trained_examples = loss_sum = 0

                if config.save_ckpt_interval and global_step % config.save_ckpt_interval == 0:
                    # NOTE: current saved checkpoint machanism is not completed,
                    # it can't restore correct dataset training status
                    save_checkpoint(
                        checkpoint_dir=config.checkpoint_dir,
                        current_epoch=epoch,
                        global_step=global_step,
                        exe=exe)

                if do_eval and global_step % config.eval_interval == 0:
                    evaluate_seq_label(
                        task,
                        data_reader,
                        feed_list,
                        phase="dev",
                        config=config)
                    evaluate_seq_label(
                        task,
                        data_reader,
                        feed_list,
                        phase="test",
                        config=config)

        # NOTE: current saved checkpoint machanism is not completed, it can't
        # resotre dataset training status
        save_checkpoint(
            checkpoint_dir=config.checkpoint_dir,
            current_epoch=num_epoch + 1,
            global_step=global_step,
            exe=exe)

        if do_eval:
            evaluate_seq_label(
                task, data_reader, feed_list, phase="test", config=config)
        logger.info("PaddleHub finetune finished.")


def evaluate_seq_label(task, data_reader, feed_list, phase="test", config=None):
    fetch_list = [
        task.variable("labels").name,
        task.variable("infers").name,
        task.variable("seq_len").name,
        task.variable("loss").name
    ]
    logger.info("Evaluation on {} dataset start".format(phase))
    inference_program = task.inference_program()
    batch_size = config.batch_size
    place, dev_count = _get_running_device_info(config)
    exe = fluid.Executor(place=place)
    with fluid.program_guard(inference_program):
        data_feeder = fluid.DataFeeder(feed_list=feed_list, place=place)
        num_eval_examples = acc_sum = loss_sum = 0
        test_reader = data_reader.data_generator(
            batch_size=batch_size, phase=phase)
        eval_time_begin = time.time()
        eval_step = 0
        total_label, total_infer, total_correct = 0.0, 0.0, 0.0
        for batch in test_reader():
            num_batch_examples = len(batch)
            eval_step += 1
            np_labels, np_infers, np_lens, _ = exe.run(
                feed=data_feeder.feed(batch), fetch_list=fetch_list)
            label_num, infer_num, correct_num = chunk_eval(
                np_labels, np_infers, np_lens, 7, dev_count)

            total_infer += infer_num
            total_label += label_num
            total_correct += correct_num

        precision, recall, f1 = calculate_f1(total_label, total_infer,
                                             total_correct)
        eval_time_used = time.time() - eval_time_begin
        eval_speed = eval_step / eval_time_used
        logger.info(
            "[%s evaluation] F1-Score=%f, precision=%f, recall=%f [step/sec: %.2f]"
            % (phase, f1, precision, recall, eval_speed))


def _finetune_cls_task(task, data_reader, feed_list, config=None,
                       do_eval=False):
W
wuzewu 已提交
208
    main_program = task.main_program()
Z
Zeyu Chen 已提交
209
    startup_program = task.startup_program()
Z
Zeyu Chen 已提交
210 211
    loss = task.variable("loss")
    accuracy = task.variable("accuracy")
W
wuzewu 已提交
212

213
    num_epoch = config.num_epoch
W
wuzewu 已提交
214
    batch_size = config.batch_size
W
wuzewu 已提交
215
    log_writter = LogWriter(
216
        os.path.join(config.checkpoint_dir, "vdllog"), sync_cycle=10)
W
wuzewu 已提交
217

218
    place, dev_count = _get_running_device_info(config)
W
wuzewu 已提交
219 220
    with fluid.program_guard(main_program, startup_program):
        exe = fluid.Executor(place=place)
Z
Zeyu Chen 已提交
221 222
        data_feeder = fluid.DataFeeder(feed_list=feed_list, place=place)

Z
Zeyu Chen 已提交
223 224 225 226
        # select strategy
        if isinstance(config.strategy, hub.BERTFinetuneStrategy):
            scheduled_lr = config.strategy.execute(loss, main_program,
                                                   data_reader, config)
W
wuzewu 已提交
227
        elif isinstance(config.strategy, hub.DefaultStrategy):
Z
Zeyu Chen 已提交
228
            config.strategy.execute(loss)
Z
Zeyu Chen 已提交
229
        #TODO: add more finetune strategy
W
wuzewu 已提交
230

231 232 233 234
        _do_memory_optimization(task, config)

        # Try to restore model training checkpoint
        current_epoch, global_step = load_checkpoint(config.checkpoint_dir, exe)
235 236 237 238

        best_eval_acc = 0.0
        train_time_used = 0
        logger.info("PaddleHub finetune start")
W
wuzewu 已提交
239 240 241 242 243 244 245 246 247

        # add visualdl scalar
        with log_writter.mode("train") as logw:
            train_loss_scalar = logw.scalar(tag="loss[train]")
            train_acc_scalar = logw.scalar(tag="accuracy[train]")
        with log_writter.mode("evaluate") as logw:
            eval_loss_scalar = logw.scalar(tag="loss[evaluate]")
            eval_acc_scalar = logw.scalar(tag="accuracy[evaluate]")

248
        # Finetune loop
249
        for epoch in range(current_epoch, num_epoch + 1):
250
            train_reader = data_reader.data_generator(
Z
Zeyu Chen 已提交
251
                batch_size=batch_size, phase='train')
252
            num_trained_examples = acc_sum = loss_sum = 0
W
wuzewu 已提交
253
            for batch in train_reader():
254 255
                num_batch_examples = len(batch)
                train_time_begin = time.time()
W
wuzewu 已提交
256
                loss_v, accuracy_v = exe.run(
W
wuzewu 已提交
257
                    feed=data_feeder.feed(batch),
W
wuzewu 已提交
258
                    fetch_list=[loss.name, accuracy.name])
259 260 261 262 263 264 265 266 267 268
                train_time_used += time.time() - train_time_begin
                global_step += 1
                num_trained_examples += num_batch_examples
                acc_sum += accuracy_v * num_batch_examples
                loss_sum += loss_v * num_batch_examples

                # log fintune status
                if global_step % config.log_interval == 0:
                    avg_loss = loss_sum / num_trained_examples
                    avg_acc = acc_sum / num_trained_examples
Z
Zeyu Chen 已提交
269
                    speed = config.log_interval / train_time_used
270 271
                    logger.info("step %d: loss=%.5f acc=%.5f [step/sec: %.2f]" %
                                (global_step, avg_loss, avg_acc, speed))
W
wuzewu 已提交
272 273

                    # record visualdl log
274 275 276 277 278 279
                    train_loss_scalar.add_record(global_step, avg_loss)
                    train_acc_scalar.add_record(global_step, avg_acc)

                    train_time_used = 0
                    num_trained_examples = acc_sum = loss_sum = 0

W
wuzewu 已提交
280
                if config.save_ckpt_interval and global_step % config.save_ckpt_interval == 0:
281 282
                    # NOTE: current saved checkpoint machanism is not completed,
                    # it can't restore dataset training status
W
wuzewu 已提交
283
                    save_checkpoint(
284 285 286 287
                        checkpoint_dir=config.checkpoint_dir,
                        current_epoch=epoch,
                        global_step=global_step,
                        exe=exe)
W
wuzewu 已提交
288

289
                if do_eval and global_step % config.eval_interval == 0:
W
wuzewu 已提交
290
                    eval_loss, eval_acc, eval_perf = evaluate(
W
wuzewu 已提交
291
                        task,
292
                        data_reader,
W
wuzewu 已提交
293
                        feed_list,
294
                        phase="val",
W
wuzewu 已提交
295
                        config=config)
296 297
                    eval_loss_scalar.add_record(global_step, eval_loss)
                    eval_acc_scalar.add_record(global_step, eval_acc)
W
wuzewu 已提交
298 299
                    if eval_acc > best_eval_acc:
                        best_eval_acc = eval_acc
300
                        model_saved_dir = os.path.join(config.checkpoint_dir,
301 302 303 304 305
                                                       "best_model")
                        logger.info(
                            "best model saved to %s [best accuracy=%.5f]" %
                            (model_saved_dir, best_eval_acc))
                        fluid.io.save_persistables(exe, dirname=model_saved_dir)
W
wuzewu 已提交
306

307 308
        # NOTE: current saved checkpoint machanism is not completed, it can't
        # resotre dataset training status
W
wuzewu 已提交
309
        save_checkpoint(
310 311 312 313
            checkpoint_dir=config.checkpoint_dir,
            current_epoch=num_epoch + 1,
            global_step=global_step,
            exe=exe)
314 315

        if do_eval:
316
            evaluate(task, data_reader, feed_list, phase="test", config=config)
317
        logger.info("PaddleHub finetune finished.")
W
wuzewu 已提交
318 319


320
def finetune_and_eval(task, data_reader, feed_list, config=None):
321 322 323 324 325
    if task.task_type == "sequence_labeling":
        _finetune_seq_label_task(
            task, data_reader, feed_list, config, do_eval=True)
    else:
        _finetune_cls_task(task, data_reader, feed_list, config, do_eval=True)
W
wuzewu 已提交
326 327


328
def finetune(task, data_reader, feed_list, config=None):
329
    _finetune_cls_task(task, data_reader, feed_list, config, do_eval=False)
W
wuzewu 已提交
330 331


332
def evaluate(task, data_reader, feed_list, phase="test", config=None):
333
    logger.info("Evaluation on {} dataset start".format(phase))
W
wuzewu 已提交
334 335 336 337 338
    inference_program = task.inference_program()
    main_program = task.main_program()
    loss = task.variable("loss")
    accuracy = task.variable("accuracy")
    batch_size = config.batch_size
339 340
    place, dev_count = _get_running_device_info(config)
    exe = fluid.Executor(place=place)
W
wuzewu 已提交
341 342
    with fluid.program_guard(inference_program):
        data_feeder = fluid.DataFeeder(feed_list=feed_list, place=place)
343
        num_eval_examples = acc_sum = loss_sum = 0
344
        test_reader = data_reader.data_generator(
W
wuzewu 已提交
345
            batch_size=batch_size, phase=phase)
W
wuzewu 已提交
346
        eval_time_begin = time.time()
347 348 349 350 351 352 353 354 355 356
        eval_step = 0
        for batch in test_reader():
            num_batch_examples = len(batch)
            eval_step += 1
            loss_v, accuracy_v = exe.run(
                feed=data_feeder.feed(batch),
                fetch_list=[loss.name, accuracy.name])
            num_eval_examples += num_batch_examples
            acc_sum += accuracy_v * num_batch_examples
            loss_sum += loss_v * num_batch_examples
W
wuzewu 已提交
357
        eval_time_used = time.time() - eval_time_begin
W
wuzewu 已提交
358

359 360 361
        avg_loss = loss_sum / num_eval_examples
        avg_acc = acc_sum / num_eval_examples
        eval_speed = eval_step / eval_time_used
362 363 364
    logger.info(
        "[%s dataset evaluation result] loss=%.5f acc=%.5f [step/sec: %.2f]" %
        (phase, avg_loss, avg_acc, eval_speed))
365 366

    return avg_loss, avg_acc, eval_speed
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470


# Sequence label evaluation functions
def chunk_eval(np_labels, np_infers, np_lens, tag_num, dev_count=1):
    def extract_bio_chunk(seq):
        chunks = []
        cur_chunk = None
        null_index = tag_num - 1
        for index in range(len(seq)):
            tag = seq[index]
            tag_type = tag // 2
            tag_pos = tag % 2

            if tag == null_index:
                if cur_chunk is not None:
                    chunks.append(cur_chunk)
                    cur_chunk = None
                continue

            if tag_pos == 0:
                if cur_chunk is not None:
                    chunks.append(cur_chunk)
                    cur_chunk = {}
                cur_chunk = {"st": index, "en": index + 1, "type": tag_type}

            else:
                if cur_chunk is None:
                    cur_chunk = {"st": index, "en": index + 1, "type": tag_type}
                    continue

                if cur_chunk["type"] == tag_type:
                    cur_chunk["en"] = index + 1
                else:
                    chunks.append(cur_chunk)
                    cur_chunk = {"st": index, "en": index + 1, "type": tag_type}

        if cur_chunk is not None:
            chunks.append(cur_chunk)
        return chunks

    null_index = tag_num - 1
    num_label = 0
    num_infer = 0
    num_correct = 0
    labels = np_labels.reshape([-1]).astype(np.int32).tolist()
    infers = np_infers.reshape([-1]).astype(np.int32).tolist()
    all_lens = np_lens.reshape([dev_count, -1]).astype(np.int32).tolist()

    base_index = 0
    for dev_index in range(dev_count):
        lens = all_lens[dev_index]
        max_len = 0
        for l in lens:
            max_len = max(max_len, l)

        for i in range(len(lens)):
            seq_st = base_index + i * max_len + 1
            seq_en = seq_st + (lens[i] - 2)
            infer_chunks = extract_bio_chunk(infers[seq_st:seq_en])
            label_chunks = extract_bio_chunk(labels[seq_st:seq_en])
            num_infer += len(infer_chunks)
            num_label += len(label_chunks)

            infer_index = 0
            label_index = 0
            while label_index < len(label_chunks) \
                   and infer_index < len(infer_chunks):
                if infer_chunks[infer_index]["st"] \
                    < label_chunks[label_index]["st"]:
                    infer_index += 1
                elif infer_chunks[infer_index]["st"] \
                    > label_chunks[label_index]["st"]:
                    label_index += 1
                else:
                    if infer_chunks[infer_index]["en"] \
                        == label_chunks[label_index]["en"] \
                        and infer_chunks[infer_index]["type"] \
                        == label_chunks[label_index]["type"]:
                        num_correct += 1

                    infer_index += 1
                    label_index += 1

        base_index += max_len * len(lens)

    return num_label, num_infer, num_correct


def calculate_f1(num_label, num_infer, num_correct):
    if num_infer == 0:
        precision = 0.0
    else:
        precision = num_correct * 1.0 / num_infer

    if num_label == 0:
        recall = 0.0
    else:
        recall = num_correct * 1.0 / num_label

    if num_correct == 0:
        f1 = 0.0
    else:
        f1 = 2 * precision * recall / (precision + recall)
    return precision, recall, f1