train.py 5.3 KB
Newer Older
L
LDOUBLEV 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# Copyright (c) 2020 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
W
WenmuZhou 已提交
21

22
__dir__ = os.path.dirname(os.path.abspath(__file__))
L
LDOUBLEV 已提交
23
sys.path.append(__dir__)
littletomatodonkey's avatar
littletomatodonkey 已提交
24
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..')))
L
LDOUBLEV 已提交
25

W
WenmuZhou 已提交
26 27 28
import yaml
import paddle
import paddle.distributed as dist
L
LDOUBLEV 已提交
29

W
WenmuZhou 已提交
30
from ppocr.data import build_dataloader
D
dyning 已提交
31 32
from ppocr.modeling.architectures import build_model
from ppocr.losses import build_loss
W
WenmuZhou 已提交
33 34 35
from ppocr.optimizer import build_optimizer
from ppocr.postprocess import build_post_process
from ppocr.metrics import build_metric
36
from ppocr.utils.save_load import load_model
文幕地方's avatar
文幕地方 已提交
37
from ppocr.utils.utility import set_seed
W
WenmuZhou 已提交
38
import tools.program as program
L
LDOUBLEV 已提交
39

W
WenmuZhou 已提交
40
dist.get_world_size()
L
LDOUBLEV 已提交
41 42


W
WenmuZhou 已提交
43 44 45 46
def main(config, device, logger, vdl_writer):
    # init dist environment
    if config['Global']['distributed']:
        dist.init_parallel_env()
L
LDOUBLEV 已提交
47

W
WenmuZhou 已提交
48
    global_config = config['Global']
D
dyning 已提交
49

W
WenmuZhou 已提交
50
    # build dataloader
D
dyning 已提交
51
    train_dataloader = build_dataloader(config, 'Train', device, logger)
W
WenmuZhou 已提交
52 53
    if len(train_dataloader) == 0:
        logger.error(
54 55 56 57
            "No Images in train dataset, please ensure\n" +
            "\t1. The images num in the train label_file_list should be larger than or equal with batch size.\n"
            +
            "\t2. The annotation file and path in the configuration file are provided normally."
W
WenmuZhou 已提交
58
        )
W
WenmuZhou 已提交
59
        return
W
WenmuZhou 已提交
60

D
dyning 已提交
61
    if config['Eval']:
D
dyning 已提交
62
        valid_dataloader = build_dataloader(config, 'Eval', device, logger)
W
WenmuZhou 已提交
63
    else:
D
dyning 已提交
64 65
        valid_dataloader = None

W
WenmuZhou 已提交
66
    # build post process
D
dyning 已提交
67 68 69
    post_process_class = build_post_process(config['PostProcess'],
                                            global_config)

W
WenmuZhou 已提交
70
    # build model
W
WenmuZhou 已提交
71
    # for rec algorithm
W
WenmuZhou 已提交
72
    if hasattr(post_process_class, 'character'):
D
dyning 已提交
73
        char_num = len(getattr(post_process_class, 'character'))
littletomatodonkey's avatar
littletomatodonkey 已提交
74 75 76 77 78 79 80 81
        if config['Architecture']["algorithm"] in ["Distillation",
                                                   ]:  # distillation model
            for key in config['Architecture']["Models"]:
                config['Architecture']["Models"][key]["Head"][
                    'out_channels'] = char_num
        else:  # base rec model
            config['Architecture']["Head"]['out_channels'] = char_num

W
WenmuZhou 已提交
82 83 84 85
    model = build_model(config['Architecture'])
    if config['Global']['distributed']:
        model = paddle.DataParallel(model)

D
dyning 已提交
86 87
    # build loss
    loss_class = build_loss(config['Loss'])
D
dyning 已提交
88

W
WenmuZhou 已提交
89
    # build optim
D
dyning 已提交
90 91
    optimizer, lr_scheduler = build_optimizer(
        config['Optimizer'],
W
WenmuZhou 已提交
92
        epochs=config['Global']['epoch_num'],
D
dyning 已提交
93
        step_each_epoch=len(train_dataloader),
W
WenmuZhou 已提交
94 95 96 97
        parameters=model.parameters())

    # build metric
    eval_class = build_metric(config['Metric'])
D
dyning 已提交
98
    # load pretrain model
99 100
    pre_best_model_dict = load_model(config, model, optimizer,
                                     config['Architecture']["model_type"])
101 102 103 104
    logger.info('train dataloader has {} iters'.format(len(train_dataloader)))
    if valid_dataloader is not None:
        logger.info('valid dataloader has {} iters'.format(
            len(valid_dataloader)))
S
stephon 已提交
105

S
stephon 已提交
106
    use_amp = config["Global"].get("use_amp", False)
S
stephon 已提交
107 108 109 110 111 112
    if use_amp:
        AMP_RELATED_FLAGS_SETTING = {
            'FLAGS_cudnn_batchnorm_spatial_persistent': 1,
            'FLAGS_max_inplace_grad_add': 8,
        }
        paddle.fluid.set_flags(AMP_RELATED_FLAGS_SETTING)
S
stephon 已提交
113 114 115
        scale_loss = config["Global"].get("scale_loss", 1.0)
        use_dynamic_loss_scaling = config["Global"].get(
            "use_dynamic_loss_scaling", False)
S
stephon 已提交
116 117 118 119 120 121
        scaler = paddle.amp.GradScaler(
            init_loss_scaling=scale_loss,
            use_dynamic_loss_scaling=use_dynamic_loss_scaling)
    else:
        scaler = None

W
WenmuZhou 已提交
122
    # start train
D
dyning 已提交
123 124
    program.train(config, train_dataloader, valid_dataloader, device, model,
                  loss_class, optimizer, lr_scheduler, post_process_class,
S
stephon 已提交
125
                  eval_class, pre_best_model_dict, logger, vdl_writer, scaler)
D
dyning 已提交
126 127 128


def test_reader(config, device, logger):
W
WenmuZhou 已提交
129
    loader = build_dataloader(config, 'Train', device, logger)
130 131 132 133
    import time
    starttime = time.time()
    count = 0
    try:
D
dyning 已提交
134
        for data in loader():
135 136 137 138
            count += 1
            if count % 1 == 0:
                batch_time = time.time() - starttime
                starttime = time.time()
W
WenmuZhou 已提交
139 140
                logger.info("reader: {}, {}, {}".format(
                    count, len(data[0]), batch_time))
141
    except Exception as e:
L
LDOUBLEV 已提交
142 143
        logger.info(e)
    logger.info("finish reader: {}, Success!".format(count))
144

D
dyning 已提交
145

L
LDOUBLEV 已提交
146
if __name__ == '__main__':
147
    config, device, logger, vdl_writer = program.preprocess(is_train=True)
文幕地方's avatar
文幕地方 已提交
148 149
    seed = config['Global']['seed'] if 'seed' in config['Global'] else 1024
    set_seed(seed)
D
dyning 已提交
150
    main(config, device, logger, vdl_writer)
W
WenmuZhou 已提交
151
    # test_reader(config, device, logger)