base.py 25.2 KB
Newer Older
F
FlyingQianMM 已提交
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
F
FlyingQianMM 已提交
2
#
F
FlyingQianMM 已提交
3 4 5
# 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
F
FlyingQianMM 已提交
6
#
F
FlyingQianMM 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
F
FlyingQianMM 已提交
8
#
F
FlyingQianMM 已提交
9 10 11 12 13
# 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.
J
jiangjiajun 已提交
14 15 16 17

from __future__ import absolute_import
import paddle.fluid as fluid
import os
S
sunyanfang01 已提交
18
import sys
J
jiangjiajun 已提交
19 20 21 22 23 24 25 26 27
import numpy as np
import time
import math
import yaml
import copy
import json
import functools
import paddlex.utils.logging as logging
from paddlex.utils import seconds_to_hms
F
FlyingQianMM 已提交
28
from paddlex.utils.utils import EarlyStop
29
from paddlex.cv.transforms import arrange_transforms
J
jiangjiajun 已提交
30 31 32 33 34 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 73 74
import paddlex
from collections import OrderedDict
from os import path as osp
from paddle.fluid.framework import Program
from .utils.pretrain_weights import get_pretrain_weights


def dict2str(dict_input):
    out = ''
    for k, v in dict_input.items():
        try:
            v = round(float(v), 6)
        except:
            pass
        out = out + '{}={}, '.format(k, v)
    return out.strip(', ')


class BaseAPI:
    def __init__(self, model_type):
        self.model_type = model_type
        # 现有的CV模型都有这个属性,而这个属且也需要在eval时用到
        self.num_classes = None
        self.labels = None
        self.version = paddlex.__version__
        if paddlex.env_info['place'] == 'cpu':
            self.places = fluid.cpu_places()
        else:
            self.places = fluid.cuda_places()
        self.exe = fluid.Executor(self.places[0])
        self.train_prog = None
        self.test_prog = None
        self.parallel_train_prog = None
        self.train_inputs = None
        self.test_inputs = None
        self.train_outputs = None
        self.test_outputs = None
        self.train_data_loader = None
        self.eval_metrics = None
        # 若模型是从inference model加载进来的,无法调用训练接口进行训练
        self.trainable = True
        # 是否使用多卡间同步BatchNorm均值和方差
        self.sync_bn = False
        # 当前模型状态
        self.status = 'Normal'
75 76
        # 已完成迭代轮数,为恢复训练时的起始轮数
        self.completed_epochs = 0
J
jiangjiajun 已提交
77
        self.scope = fluid.global_scope()
J
jiangjiajun 已提交
78 79 80 81 82 83

    def _get_single_card_bs(self, batch_size):
        if batch_size % len(self.places) == 0:
            return int(batch_size // len(self.places))
        else:
            raise Exception("Please support correct batch_size, \
84 85 86
                            which can be divided by available cards({}) in {}"
                            .format(paddlex.env_info['num'], paddlex.env_info[
                                'place']))
J
jiangjiajun 已提交
87 88

    def build_program(self):
J
jiangjiajun 已提交
89 90 91 92
        if hasattr(paddlex, 'model_built') and paddlex.model_built:
            logging.error(
                "Function model.train() only can be called once in your code.")
        paddlex.model_built = True
J
jiangjiajun 已提交
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
        # 构建训练网络
        self.train_inputs, self.train_outputs = self.build_net(mode='train')
        self.train_prog = fluid.default_main_program()
        startup_prog = fluid.default_startup_program()

        # 构建预测网络
        self.test_prog = fluid.Program()
        with fluid.program_guard(self.test_prog, startup_prog):
            with fluid.unique_name.guard():
                self.test_inputs, self.test_outputs = self.build_net(
                    mode='test')
        self.test_prog = self.test_prog.clone(for_test=True)

    def build_train_data_loader(self, dataset, batch_size):
        # 初始化data_loader
        if self.train_data_loader is None:
            self.train_data_loader = fluid.io.DataLoader.from_generator(
                feed_list=list(self.train_inputs.values()),
                capacity=64,
                use_double_buffer=True,
                iterable=True)
        batch_size_each_gpu = self._get_single_card_bs(batch_size)
        generator = dataset.generator(
            batch_size=batch_size_each_gpu, drop_last=True)
        self.train_data_loader.set_sample_list_generator(
            dataset.generator(batch_size=batch_size_each_gpu),
            places=self.places)

    def export_quant_model(self,
                           dataset,
                           save_dir,
                           batch_size=1,
                           batch_num=10,
                           cache_dir="./temp"):
127 128 129 130 131
        arrange_transforms(
            model_type=self.model_type,
            class_name=self.__class__.__name__,
            transforms=dataset.transforms,
            mode='quant')
J
jiangjiajun 已提交
132 133 134
        dataset.num_samples = batch_size * batch_num
        try:
            from .slim.post_quantization import PaddleXPostTrainingQuantization
S
sunyanfang01 已提交
135
            PaddleXPostTrainingQuantization._collect_target_varnames
J
jiangjiajun 已提交
136 137
        except:
            raise Exception(
S
sunyanfang01 已提交
138
                "Model Quantization is not available, try to upgrade your paddlepaddle>=1.8.0"
J
jiangjiajun 已提交
139 140 141 142 143 144 145 146 147 148 149 150
            )
        is_use_cache_file = True
        if cache_dir is None:
            is_use_cache_file = False
        post_training_quantization = PaddleXPostTrainingQuantization(
            executor=self.exe,
            dataset=dataset,
            program=self.test_prog,
            inputs=self.test_inputs,
            outputs=self.test_outputs,
            batch_size=batch_size,
            batch_nums=batch_num,
J
jiangjiajun 已提交
151
            scope=self.scope,
J
jiangjiajun 已提交
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
            algo='KL',
            quantizable_op_type=["conv2d", "depthwise_conv2d", "mul"],
            is_full_quantize=False,
            is_use_cache_file=is_use_cache_file,
            cache_dir=cache_dir)
        post_training_quantization.quantize()
        post_training_quantization.save_quantized_model(save_dir)
        model_info = self.get_model_info()
        model_info['status'] = 'Quant'

        # 保存模型输出的变量描述
        model_info['_ModelInputsOutputs'] = dict()
        model_info['_ModelInputsOutputs']['test_inputs'] = [
            [k, v.name] for k, v in self.test_inputs.items()
        ]
        model_info['_ModelInputsOutputs']['test_outputs'] = [
            [k, v.name] for k, v in self.test_outputs.items()
        ]

        with open(
                osp.join(save_dir, 'model.yml'), encoding='utf-8',
                mode='w') as f:
            yaml.dump(model_info, f)

    def net_initialize(self,
                       startup_prog=None,
                       pretrain_weights=None,
                       fuse_bn=False,
                       save_dir='.',
                       sensitivities_file=None,
182 183 184 185 186 187 188 189
                       eval_metric_loss=0.05,
                       resume_checkpoint=None):
        if not resume_checkpoint:
            pretrain_dir = osp.join(save_dir, 'pretrain')
            if not os.path.isdir(pretrain_dir):
                if os.path.exists(pretrain_dir):
                    os.remove(pretrain_dir)
                os.makedirs(pretrain_dir)
F
FlyingQianMM 已提交
190 191
            if pretrain_weights is not None and not os.path.exists(
                    pretrain_weights):
192 193 194
                if self.model_type == 'classifier':
                    if pretrain_weights not in ['IMAGENET']:
                        logging.warning(
J
jiangjiajun 已提交
195
                            "Path of pretrain_weights('{}') is not exists!".
196
                            format(pretrain_weights))
J
jiangjiajun 已提交
197 198 199
                        logging.warning(
                            "Pretrain_weights will be forced to set as 'IMAGENET', if you don't want to use pretrain weights, set pretrain_weights=None."
                        )
200 201 202 203
                        pretrain_weights = 'IMAGENET'
                elif self.model_type == 'detector':
                    if pretrain_weights not in ['IMAGENET', 'COCO']:
                        logging.warning(
J
jiangjiajun 已提交
204
                            "Path of pretrain_weights('{}') is not exists!".
205
                            format(pretrain_weights))
J
jiangjiajun 已提交
206 207 208
                        logging.warning(
                            "Pretrain_weights will be forced to set as 'IMAGENET', if you don't want to use pretrain weights, set pretrain_weights=None."
                        )
209 210 211 212 213 214
                        pretrain_weights = 'IMAGENET'
                elif self.model_type == 'segmenter':
                    if pretrain_weights not in [
                            'IMAGENET', 'COCO', 'CITYSCAPES'
                    ]:
                        logging.warning(
J
jiangjiajun 已提交
215
                            "Path of pretrain_weights('{}') is not exists!".
216
                            format(pretrain_weights))
J
jiangjiajun 已提交
217 218 219
                        logging.warning(
                            "Pretrain_weights will be forced to set as 'IMAGENET', if you don't want to use pretrain weights, set pretrain_weights=None."
                        )
220
                        pretrain_weights = 'IMAGENET'
221 222 223 224
            if hasattr(self, 'backbone'):
                backbone = self.backbone
            else:
                backbone = self.__class__.__name__
F
FlyingQianMM 已提交
225 226
                if backbone == "HRNet":
                    backbone = backbone + "_W{}".format(self.width)
227
            class_name = self.__class__.__name__
228
            pretrain_weights = get_pretrain_weights(
229
                pretrain_weights, class_name, backbone, pretrain_dir)
J
jiangjiajun 已提交
230 231 232
        if startup_prog is None:
            startup_prog = fluid.default_startup_program()
        self.exe.run(startup_prog)
233 234 235 236 237 238 239
        if resume_checkpoint:
            logging.info(
                "Resume checkpoint from {}.".format(resume_checkpoint),
                use_color=True)
            paddlex.utils.utils.load_pretrain_weights(
                self.exe, self.train_prog, resume_checkpoint, resume=True)
            if not osp.exists(osp.join(resume_checkpoint, "model.yml")):
240 241
                raise Exception("There's not model.yml in {}".format(
                    resume_checkpoint))
242 243 244 245
            with open(osp.join(resume_checkpoint, "model.yml")) as f:
                info = yaml.load(f.read(), Loader=yaml.Loader)
                self.completed_epochs = info['completed_epochs']
        elif pretrain_weights is not None:
J
jiangjiajun 已提交
246
            logging.info(
C
Channingss 已提交
247 248
                "Load pretrain weights from {}.".format(pretrain_weights),
                use_color=True)
J
jiangjiajun 已提交
249 250
            paddlex.utils.utils.load_pretrain_weights(self.exe, self.train_prog,
                                                      pretrain_weights, fuse_bn)
J
jiangjiajun 已提交
251 252
        # 进行裁剪
        if sensitivities_file is not None:
J
jiangjiajun 已提交
253
            import paddleslim
J
jiangjiajun 已提交
254 255 256 257
            from .slim.prune_config import get_sensitivities
            sensitivities_file = get_sensitivities(sensitivities_file, self,
                                                   save_dir)
            from .slim.prune import get_params_ratios, prune_program
J
jiangjiajun 已提交
258 259
            logging.info(
                "Start to prune program with eval_metric_loss = {}".format(
C
Channingss 已提交
260 261
                    eval_metric_loss),
                use_color=True)
J
jiangjiajun 已提交
262
            origin_flops = paddleslim.analysis.flops(self.test_prog)
J
jiangjiajun 已提交
263 264 265
            prune_params_ratios = get_params_ratios(
                sensitivities_file, eval_metric_loss=eval_metric_loss)
            prune_program(self, prune_params_ratios)
J
jiangjiajun 已提交
266 267 268 269
            current_flops = paddleslim.analysis.flops(self.test_prog)
            remaining_ratio = current_flops / origin_flops
            logging.info(
                "Finish prune program, before FLOPs:{}, after prune FLOPs:{}, remaining ratio:{}"
C
Channingss 已提交
270 271
                .format(origin_flops, current_flops, remaining_ratio),
                use_color=True)
J
jiangjiajun 已提交
272 273 274 275 276 277 278 279 280 281 282
            self.status = 'Prune'

    def get_model_info(self):
        info = dict()
        info['version'] = paddlex.__version__
        info['Model'] = self.__class__.__name__
        info['_Attributes'] = {'model_type': self.model_type}
        if 'self' in self.init_params:
            del self.init_params['self']
        if '__class__' in self.init_params:
            del self.init_params['__class__']
S
sunyanfang01 已提交
283 284 285
        if 'model_name' in self.init_params:
            del self.init_params['model_name']

J
jiangjiajun 已提交
286 287 288 289
        info['_init_params'] = self.init_params

        info['_Attributes']['num_classes'] = self.num_classes
        info['_Attributes']['labels'] = self.labels
J
jiangjiajun 已提交
290
        info['_Attributes']['fixed_input_shape'] = self.fixed_input_shape
J
jiangjiajun 已提交
291 292 293 294 295 296 297 298 299 300
        try:
            primary_metric_key = list(self.eval_metrics.keys())[0]
            primary_metric_value = float(self.eval_metrics[primary_metric_key])
            info['_Attributes']['eval_metrics'] = {
                primary_metric_key: primary_metric_value
            }
        except:
            pass

        if hasattr(self, 'test_transforms'):
301 302 303 304 305 306
            if hasattr(self.test_transforms, 'to_rgb'):
                if self.test_transforms.to_rgb:
                    info['TransformsMode'] = 'RGB'
                else:
                    info['TransformsMode'] = 'BGR'

J
jiangjiajun 已提交
307 308 309 310 311 312
            if self.test_transforms is not None:
                info['Transforms'] = list()
                for op in self.test_transforms.transforms:
                    name = op.__class__.__name__
                    attr = op.__dict__
                    info['Transforms'].append({name: attr})
313
        info['completed_epochs'] = self.completed_epochs
J
jiangjiajun 已提交
314 315 316 317 318 319 320
        return info

    def save_model(self, save_dir):
        if not osp.isdir(save_dir):
            if osp.exists(save_dir):
                os.remove(save_dir)
            os.makedirs(save_dir)
J
jiangjiajun 已提交
321 322 323 324
        if self.train_prog is not None:
            fluid.save(self.train_prog, osp.join(save_dir, 'model'))
        else:
            fluid.save(self.test_prog, osp.join(save_dir, 'model'))
J
jiangjiajun 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        model_info = self.get_model_info()
        model_info['status'] = self.status
        with open(
                osp.join(save_dir, 'model.yml'), encoding='utf-8',
                mode='w') as f:
            yaml.dump(model_info, f)
        # 评估结果保存
        if hasattr(self, 'eval_details'):
            with open(osp.join(save_dir, 'eval_details.json'), 'w') as f:
                json.dump(self.eval_details, f)

        if self.status == 'Prune':
            # 保存裁剪的shape
            shapes = {}
            for block in self.train_prog.blocks:
                for param in block.all_parameters():
                    pd_var = fluid.global_scope().find_var(param.name)
                    pd_param = pd_var.get_tensor()
                    shapes[param.name] = np.array(pd_param).shape
            with open(
                    osp.join(save_dir, 'prune.yml'), encoding='utf-8',
                    mode='w') as f:
                yaml.dump(shapes, f)

        # 模型保存成功的标志
        open(osp.join(save_dir, '.success'), 'w').close()
        logging.info("Model saved in {}.".format(save_dir))

C
Channingss 已提交
353
    def export_inference_model(self, save_dir):
J
jiangjiajun 已提交
354
        test_input_names = [var.name for var in list(self.test_inputs.values())]
J
jiangjiajun 已提交
355
        test_outputs = list(self.test_outputs.values())
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
        with fluid.scope_guard(self.scope):
            if self.__class__.__name__ == 'MaskRCNN':
                from paddlex.utils.save import save_mask_inference_model
                save_mask_inference_model(
                    dirname=save_dir,
                    executor=self.exe,
                    params_filename='__params__',
                    feeded_var_names=test_input_names,
                    target_vars=test_outputs,
                    main_program=self.test_prog)
            else:
                fluid.io.save_inference_model(
                    dirname=save_dir,
                    executor=self.exe,
                    params_filename='__params__',
                    feeded_var_names=test_input_names,
                    target_vars=test_outputs,
                    main_program=self.test_prog)
J
jiangjiajun 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        model_info = self.get_model_info()
        model_info['status'] = 'Infer'

        # 保存模型输出的变量描述
        model_info['_ModelInputsOutputs'] = dict()
        model_info['_ModelInputsOutputs']['test_inputs'] = [
            [k, v.name] for k, v in self.test_inputs.items()
        ]
        model_info['_ModelInputsOutputs']['test_outputs'] = [
            [k, v.name] for k, v in self.test_outputs.items()
        ]
        with open(
                osp.join(save_dir, 'model.yml'), encoding='utf-8',
                mode='w') as f:
            yaml.dump(model_info, f)
C
Channingss 已提交
389

J
jiangjiajun 已提交
390 391
        # 模型保存成功的标志
        open(osp.join(save_dir, '.success'), 'w').close()
J
jiangjiajun 已提交
392
        logging.info("Model for inference deploy saved in {}.".format(save_dir))
J
jiangjiajun 已提交
393 394 395 396 397 398 399 400 401

    def train_loop(self,
                   num_epochs,
                   train_dataset,
                   train_batch_size,
                   eval_dataset=None,
                   save_interval_epochs=1,
                   log_interval_steps=10,
                   save_dir='output',
F
FlyingQianMM 已提交
402 403 404
                   use_vdl=False,
                   early_stop=False,
                   early_stop_patience=5):
S
sunyanfang01 已提交
405
        if train_dataset.num_samples < train_batch_size:
406 407
            raise Exception(
                'The amount of training datset must be larger than batch size.')
J
jiangjiajun 已提交
408 409 410 411 412 413 414 415
        if not osp.isdir(save_dir):
            if osp.exists(save_dir):
                os.remove(save_dir)
            os.makedirs(save_dir)
        if use_vdl:
            from visualdl import LogWriter
            vdl_logdir = osp.join(save_dir, 'vdl_log')
        # 给transform添加arrange操作
416 417 418 419 420
        arrange_transforms(
            model_type=self.model_type,
            class_name=self.__class__.__name__,
            transforms=train_dataset.transforms,
            mode='train')
J
jiangjiajun 已提交
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
        # 构建train_data_loader
        self.build_train_data_loader(
            dataset=train_dataset, batch_size=train_batch_size)

        if eval_dataset is not None:
            self.eval_transforms = eval_dataset.transforms
            self.test_transforms = copy.deepcopy(eval_dataset.transforms)

        # 获取实时变化的learning rate
        lr = self.optimizer._learning_rate
        if isinstance(lr, fluid.framework.Variable):
            self.train_outputs['lr'] = lr

        # 在多卡上跑训练
        if self.parallel_train_prog is None:
            build_strategy = fluid.compiler.BuildStrategy()
            build_strategy.fuse_all_optimizer_ops = False
            if paddlex.env_info['place'] != 'cpu' and len(self.places) > 1:
                build_strategy.sync_batch_norm = self.sync_bn
            exec_strategy = fluid.ExecutionStrategy()
            exec_strategy.num_iteration_per_drop_scope = 1
            self.parallel_train_prog = fluid.CompiledProgram(
                self.train_prog).with_data_parallel(
                    loss_name=self.train_outputs['loss'].name,
                    build_strategy=build_strategy,
                    exec_strategy=exec_strategy)

448 449
        total_num_steps = math.floor(train_dataset.num_samples /
                                     train_batch_size)
J
jiangjiajun 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462
        num_steps = 0
        time_stat = list()
        time_train_one_epoch = None
        time_eval_one_epoch = None

        total_num_steps_eval = 0
        # 模型总共的评估次数
        total_eval_times = math.ceil(num_epochs / save_interval_epochs)
        # 检测目前仅支持单卡评估,训练数据batch大小与显卡数量之商为验证数据batch大小。
        eval_batch_size = train_batch_size
        if self.model_type == 'detector':
            eval_batch_size = self._get_single_card_bs(train_batch_size)
        if eval_dataset is not None:
463 464
            total_num_steps_eval = math.ceil(eval_dataset.num_samples /
                                             eval_batch_size)
J
jiangjiajun 已提交
465 466 467

        if use_vdl:
            # VisualDL component
S
sunyanfang01 已提交
468
            log_writer = LogWriter(vdl_logdir)
J
jiangjiajun 已提交
469

F
FlyingQianMM 已提交
470 471 472
        thresh = 0.0001
        if early_stop:
            earlystop = EarlyStop(early_stop_patience, thresh)
J
jiangjiajun 已提交
473 474
        best_accuracy_key = ""
        best_accuracy = -1.0
J
jiangjiajun 已提交
475
        best_model_epoch = -1
F
FlyingQianMM 已提交
476
        start_epoch = self.completed_epochs
477
        for i in range(start_epoch, num_epochs):
J
jiangjiajun 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
            records = list()
            step_start_time = time.time()
            epoch_start_time = time.time()
            for step, data in enumerate(self.train_data_loader()):
                outputs = self.exe.run(
                    self.parallel_train_prog,
                    feed=data,
                    fetch_list=list(self.train_outputs.values()))
                outputs_avg = np.mean(np.array(outputs), axis=1)
                records.append(outputs_avg)

                # 训练完成剩余时间预估
                current_time = time.time()
                step_cost_time = current_time - step_start_time
                step_start_time = current_time
                if len(time_stat) < 20:
                    time_stat.append(step_cost_time)
                else:
                    time_stat[num_steps % 20] = step_cost_time

                # 每间隔log_interval_steps,输出loss信息
                num_steps += 1
                if num_steps % log_interval_steps == 0:
                    step_metrics = OrderedDict(
                        zip(list(self.train_outputs.keys()), outputs_avg))

                    if use_vdl:
                        for k, v in step_metrics.items():
506 507 508
                            log_writer.add_scalar(
                                'Metrics/Training(Step): {}'.format(k), v,
                                num_steps)
J
jiangjiajun 已提交
509 510 511 512 513 514 515

                    # 估算剩余时间
                    avg_step_time = np.mean(time_stat)
                    if time_train_one_epoch is not None:
                        eta = (num_epochs - i - 1) * time_train_one_epoch + (
                            total_num_steps - step - 1) * avg_step_time
                    else:
516 517
                        eta = ((num_epochs - i) * total_num_steps - step - 1
                               ) * avg_step_time
J
jiangjiajun 已提交
518
                    if time_eval_one_epoch is not None:
J
jiangjiajun 已提交
519 520
                        eval_eta = (total_eval_times - i // save_interval_epochs
                                    ) * time_eval_one_epoch
J
jiangjiajun 已提交
521
                    else:
J
jiangjiajun 已提交
522 523
                        eval_eta = (total_eval_times - i // save_interval_epochs
                                    ) * total_num_steps_eval * avg_step_time
J
jiangjiajun 已提交
524 525 526 527 528
                    eta_str = seconds_to_hms(eta + eval_eta)

                    logging.info(
                        "[TRAIN] Epoch={}/{}, Step={}/{}, {}, time_each_step={}s, eta={}"
                        .format(i + 1, num_epochs, step + 1, total_num_steps,
529 530
                                dict2str(step_metrics),
                                round(avg_step_time, 2), eta_str))
J
jiangjiajun 已提交
531
            train_metrics = OrderedDict(
532 533
                zip(list(self.train_outputs.keys()), np.mean(
                    records, axis=0)))
J
jiangjiajun 已提交
534 535 536 537 538 539
            logging.info('[TRAIN] Epoch {} finished, {} .'.format(
                i + 1, dict2str(train_metrics)))
            time_train_one_epoch = time.time() - epoch_start_time
            epoch_start_time = time.time()

            # 每间隔save_interval_epochs, 在验证集上评估和对模型进行保存
C
chenguowei01 已提交
540
            self.completed_epochs += 1
J
jiangjiajun 已提交
541 542 543 544 545
            eval_epoch_start_time = time.time()
            if (i + 1) % save_interval_epochs == 0 or i == num_epochs - 1:
                current_save_dir = osp.join(save_dir, "epoch_{}".format(i + 1))
                if not osp.isdir(current_save_dir):
                    os.makedirs(current_save_dir)
J
jiangjiajun 已提交
546
                if eval_dataset is not None and eval_dataset.num_samples > 0:
J
jiangjiajun 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
                    self.eval_metrics, self.eval_details = self.evaluate(
                        eval_dataset=eval_dataset,
                        batch_size=eval_batch_size,
                        epoch_id=i + 1,
                        return_details=True)
                    logging.info('[EVAL] Finished, Epoch={}, {} .'.format(
                        i + 1, dict2str(self.eval_metrics)))
                    # 保存最优模型
                    best_accuracy_key = list(self.eval_metrics.keys())[0]
                    current_accuracy = self.eval_metrics[best_accuracy_key]
                    if current_accuracy > best_accuracy:
                        best_accuracy = current_accuracy
                        best_model_epoch = i + 1
                        best_model_dir = osp.join(save_dir, "best_model")
                        self.save_model(save_dir=best_model_dir)
                    if use_vdl:
                        for k, v in self.eval_metrics.items():
                            if isinstance(v, list):
                                continue
                            if isinstance(v, np.ndarray):
                                if v.size > 1:
                                    continue
569 570
                            log_writer.add_scalar(
                                "Metrics/Eval(Epoch): {}".format(k), v, i + 1)
J
jiangjiajun 已提交
571 572 573
                self.save_model(save_dir=current_save_dir)
                time_eval_one_epoch = time.time() - eval_epoch_start_time
                eval_epoch_start_time = time.time()
J
jiangjiajun 已提交
574 575 576 577 578
                if best_model_epoch > 0:
                    logging.info(
                        'Current evaluated best model in eval_dataset is epoch_{}, {}={}'
                        .format(best_model_epoch, best_accuracy_key,
                                best_accuracy))
F
FlyingQianMM 已提交
579 580
                if eval_dataset is not None and early_stop:
                    if earlystop(current_accuracy):
581
                        break