train.py 4.7 KB
Newer Older
G
gengdongjie 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""Warpctc training"""
import os
import math as m
import random
import argparse
import numpy as np
import mindspore.nn as nn
from mindspore import context
from mindspore import dataset as de
Y
yao_yf 已提交
24 25
from mindspore.train.model import Model
from mindspore.context import ParallelMode
G
gengdongjie 已提交
26 27
from mindspore.nn.wrap import WithLossCell
from mindspore.train.callback import TimeMonitor, LossMonitor, CheckpointConfig, ModelCheckpoint
Y
yangyongjie 已提交
28
from mindspore.communication.management import init, get_group_size, get_rank
G
gengdongjie 已提交
29

Y
yangyongjie 已提交
30
from src.loss import CTCLoss, CTCLossV2
G
gengdongjie 已提交
31 32
from src.config import config as cf
from src.dataset import create_dataset
Y
yangyongjie 已提交
33
from src.warpctc import StackedRNN, StackedRNNForGPU
G
gengdongjie 已提交
34 35 36 37 38 39 40 41
from src.warpctc_for_train import TrainOneStepCellWithGradClip
from src.lr_schedule import get_lr

random.seed(1)
np.random.seed(1)
de.config.set_seed(1)

parser = argparse.ArgumentParser(description="Warpctc training")
Y
yangyongjie 已提交
42
parser.add_argument("--run_distribute", action='store_true', help="Run distribute, default is false.")
G
gengdongjie 已提交
43
parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path, default is None')
Y
yangyongjie 已提交
44 45 46
parser.add_argument('--platform', type=str, default='Ascend', choices=['Ascend', 'GPU'],
                    help='Running platform, choose from Ascend, GPU, and default is Ascend.')
parser.set_defaults(run_distribute=False)
G
gengdongjie 已提交
47 48
args_opt = parser.parse_args()

Y
yangyongjie 已提交
49 50 51 52 53
context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.platform, save_graphs=False)
if args_opt.platform == 'Ascend':
    device_id = int(os.getenv('DEVICE_ID'))
    context.set_context(device_id=device_id)

G
gengdongjie 已提交
54 55

if __name__ == '__main__':
Y
yangyongjie 已提交
56
    lr_scale = 1
G
gengdongjie 已提交
57
    if args_opt.run_distribute:
Y
yangyongjie 已提交
58 59 60 61 62 63 64 65 66 67
        if args_opt.platform == 'Ascend':
            init()
            lr_scale = 1
            device_num = int(os.environ.get("RANK_SIZE"))
            rank = int(os.environ.get("RANK_ID"))
        else:
            init('nccl')
            lr_scale = 0.5
            device_num = get_group_size()
            rank = get_rank()
G
gengdongjie 已提交
68
        context.reset_auto_parallel_context()
Y
yangyongjie 已提交
69
        context.set_auto_parallel_context(device_num=device_num,
G
gengdongjie 已提交
70 71
                                          parallel_mode=ParallelMode.DATA_PARALLEL,
                                          mirror_mean=True)
Y
yangyongjie 已提交
72 73 74 75
    else:
        device_num = 1
        rank = 0

G
gengdongjie 已提交
76 77 78
    max_captcha_digits = cf.max_captcha_digits
    input_size = m.ceil(cf.captcha_height / 64) * 64 * 3
    # create dataset
Y
yangyongjie 已提交
79 80
    dataset = create_dataset(dataset_path=args_opt.dataset_path, batch_size=cf.batch_size,
                             num_shards=device_num, shard_id=rank, device_target=args_opt.platform)
G
gengdongjie 已提交
81 82
    step_size = dataset.get_dataset_size()
    # define lr
Y
yangyongjie 已提交
83
    lr_init = cf.learning_rate if not args_opt.run_distribute else cf.learning_rate * device_num * lr_scale
G
gengdongjie 已提交
84
    lr = get_lr(cf.epoch_size, step_size, lr_init)
Y
yangyongjie 已提交
85 86 87 88 89 90 91 92 93 94 95
    if args_opt.platform == 'Ascend':
        loss = CTCLoss(max_sequence_length=cf.captcha_width,
                       max_label_length=max_captcha_digits,
                       batch_size=cf.batch_size)
        net = StackedRNN(input_size=input_size, batch_size=cf.batch_size, hidden_size=cf.hidden_size)
        opt = nn.SGD(params=net.trainable_params(), learning_rate=lr, momentum=cf.momentum)
    else:
        loss = CTCLossV2(max_sequence_length=cf.captcha_width, batch_size=cf.batch_size)
        net = StackedRNNForGPU(input_size=input_size, batch_size=cf.batch_size, hidden_size=cf.hidden_size)
        opt = nn.Momentum(params=net.trainable_params(), learning_rate=lr, momentum=cf.momentum)

G
gengdongjie 已提交
96 97 98 99 100 101 102 103 104
    net = WithLossCell(net, loss)
    net = TrainOneStepCellWithGradClip(net, opt).set_train()
    # define model
    model = Model(net)
    # define callbacks
    callbacks = [LossMonitor(), TimeMonitor(data_size=step_size)]
    if cf.save_checkpoint:
        config_ck = CheckpointConfig(save_checkpoint_steps=cf.save_checkpoint_steps,
                                     keep_checkpoint_max=cf.keep_checkpoint_max)
105
        ckpt_cb = ModelCheckpoint(prefix="warpctc", directory=cf.save_checkpoint_path + str(rank), config=config_ck)
G
gengdongjie 已提交
106 107
        callbacks.append(ckpt_cb)
    model.train(cf.epoch_size, dataset, callbacks=callbacks)