train_utils.py 6.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#   Copyright (c) 2018 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 sys
import time
import numpy as np
import paddle
import paddle.fluid as fluid
H
hysunflower 已提交
21
from paddle.fluid import profiler
22
from utils.timer import TimeAverager
23 24 25 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
import logging
import shutil

logger = logging.getLogger(__name__)


def log_lr_and_step():
    try:
        # In optimizers, if learning_rate is set as constant, lr_var
        # name is 'learning_rate_0', and iteration counter is not 
        # recorded. If learning_rate is set as decayed values from 
        # learning_rate_scheduler, lr_var name is 'learning_rate', 
        # and iteration counter is recorded with name '@LR_DECAY_COUNTER@', 
        # better impliment is required here
        lr_var = fluid.global_scope().find_var("learning_rate")
        if not lr_var:
            lr_var = fluid.global_scope().find_var("learning_rate_0")
        lr = np.array(lr_var.get_tensor())

        lr_count = '[-]'
        lr_count_var = fluid.global_scope().find_var("@LR_DECAY_COUNTER@")
        if lr_count_var:
            lr_count = np.array(lr_count_var.get_tensor())
        logger.info("------- learning rate {}, learning rate counter {} -----"
                    .format(np.array(lr), np.array(lr_count)))
    except:
        logger.warn("Unable to get learning_rate and LR_DECAY_COUNTER.")


52 53 54 55 56 57 58 59 60
def test_with_dataloader(exe,
                         compiled_test_prog,
                         test_dataloader,
                         test_fetch_list,
                         test_metrics,
                         log_interval=0,
                         save_model_name=''):
    if not test_dataloader:
        logger.error("[TEST] get dataloader failed.")
61 62 63
    test_metrics.reset()
    test_iter = 0

64
    for data in test_dataloader():
65 66 67 68 69 70 71 72 73 74 75
        test_outs = exe.run(compiled_test_prog,
                            fetch_list=test_fetch_list,
                            feed=data)
        test_metrics.accumulate(test_outs)
        if log_interval > 0 and test_iter % log_interval == 0:
            test_metrics.calculate_and_log_out(test_outs, \
               info = '[TEST] test_iter {} '.format(test_iter))
        test_iter += 1
    test_metrics.finalize_and_log_out("[TEST] Finish")


76
def train_with_dataloader(exe, train_prog, compiled_train_prog, train_dataloader, \
77 78
                        train_fetch_list, train_metrics, epochs = 10, \
                        log_interval = 0, valid_interval = 0, save_dir = './', \
79
                        num_trainers = 1, trainer_id = 0, \
80
                        save_model_name = 'model', fix_random_seed = False, \
81
                        compiled_test_prog = None, test_dataloader = None, \
H
hysunflower 已提交
82 83
                        test_fetch_list = None, test_metrics = None, \
                        is_profiler = None, profiler_path = None):
84 85
    if not train_dataloader:
        logger.error("[TRAIN] get dataloader failed.")
86

87
    train_loss = 0
88 89 90 91

    epoch_periods = []
    reader_cost_averager = TimeAverager()
    batch_cost_averager = TimeAverager()
92 93 94 95 96 97
    for epoch in range(epochs):
        log_lr_and_step()

        train_iter = 0
        epoch_periods = []

98
        batch_start = time.time()
99
        for data in train_dataloader():
100 101
            reader_cost_averager.record(time.time() - batch_start)

102 103 104
            train_outs = exe.run(compiled_train_prog,
                                 fetch_list=train_fetch_list,
                                 feed=data)
105 106 107 108 109 110 111

            batch_cost = time.time() - batch_start
            epoch_periods.append(batch_cost)
            batch_cost_averager.record(batch_cost)

            local_time = time.localtime(time.time())
            str_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
112 113
            if log_interval > 0 and (train_iter % log_interval == 0):
                train_metrics.calculate_and_log_out(train_outs, \
114 115 116 117
                        info = '[TRAIN {}] Epoch {}, iter {}, batch_cost {:.5}, reader_cost {:.5}'.format(str_time, epoch, train_iter, batch_cost_averager.get_average(), reader_cost_averager.get_average()))
                reader_cost_averager.reset()
                batch_cost_averager.reset()

118
            train_iter += 1
119
            batch_start = time.time()
120

H
hysunflower 已提交
121 122 123 124 125 126
            # NOTE: profiler tools, used for benchmark
            if is_profiler and epoch == 0 and train_iter == log_interval:
                profiler.start_profiler("All")
            elif is_profiler and epoch == 0 and train_iter == log_interval + 5:
                profiler.stop_profiler("total", profiler_path)
                return
127 128 129 130 131 132 133 134

        if len(epoch_periods) < 1:
            logger.info(
                'No iteration was executed, please check the data reader')
            sys.exit(1)

        logger.info('[TRAIN] Epoch {} training finished, average time: {}'.
                    format(epoch, np.mean(epoch_periods[1:])))
135 136 137 138

        if trainer_id == 0:
            save_model(exe, train_prog, save_dir, save_model_name,
                       "_epoch{}".format(epoch))
139 140
        if compiled_test_prog and valid_interval > 0 and (
                epoch + 1) % valid_interval == 0:
141 142 143
            test_with_dataloader(exe, compiled_test_prog, test_dataloader,
                                 test_fetch_list, test_metrics, log_interval,
                                 save_model_name)
144

145 146
    if trainer_id == 0:
        save_model(exe, train_prog, save_dir, save_model_name)
147 148 149 150 151 152 153 154 155
    #when fix_random seed for debug
    if fix_random_seed:
        cards = os.environ.get('CUDA_VISIBLE_DEVICES')
        gpu_num = len(cards.split(","))
        print("kpis\ttrain_cost_card{}\t{}".format(gpu_num, train_loss))
        print("kpis\ttrain_speed_card{}\t{}".format(gpu_num,
                                                    np.mean(epoch_periods)))


156 157
def save_model(exe, program, save_dir, model_name, postfix=''):
    """save paramters and optimizer related varaibles"""
158 159
    if not os.path.isdir(save_dir):
        os.makedirs(save_dir)
160 161 162 163
    saved_model_name = model_name + postfix

    fluid.save(program, os.path.join(save_dir, saved_model_name))

164
    return