train.py 5.8 KB
Newer Older
Y
yangyongjie 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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.
# ============================================================================
"""train_criteo."""
import os
import sys
import argparse
T
tom__chen 已提交
19 20
import random
import numpy as np
Y
yangyongjie 已提交
21

Y
yao_yf 已提交
22 23
from mindspore import context
from mindspore.context import ParallelMode
T
tom__chen 已提交
24
from mindspore.communication.management import init, get_rank, get_group_size
Y
yangyongjie 已提交
25 26
from mindspore.train.model import Model
from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, TimeMonitor
T
tom__chen 已提交
27
import mindspore.dataset.engine as de
Y
yangyongjie 已提交
28 29 30 31 32 33 34 35 36 37

from src.deepfm import ModelBuilder, AUCMetric
from src.config import DataConfig, ModelConfig, TrainConfig
from src.dataset import create_dataset, DataType
from src.callback import EvalCallBack, LossCallBack

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
parser = argparse.ArgumentParser(description='CTR Prediction')
parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
parser.add_argument('--ckpt_path', type=str, default=None, help='Checkpoint path')
Y
yangyongjie 已提交
38 39 40 41 42 43 44
parser.add_argument('--eval_file_name', type=str, default="./auc.log",
                    help='Auc log file path. Default: "./auc.log"')
parser.add_argument('--loss_file_name', type=str, default="./loss.log",
                    help='Loss log file path. Default: "./loss.log"')
parser.add_argument('--do_eval', type=str, default='True',
                    help='Do evaluation or not, only support "True" or "False". Default: "True"')
parser.add_argument('--device_target', type=str, default="Ascend", help='Ascend or GPU. Default: Ascend')
Y
yangyongjie 已提交
45
args_opt, _ = parser.parse_known_args()
Y
yangyongjie 已提交
46
args_opt.do_eval = args_opt.do_eval == 'True'
T
tom__chen 已提交
47
rank_size = int(os.environ.get("RANK_SIZE", 1))
Y
yangyongjie 已提交
48

T
tom__chen 已提交
49 50 51
random.seed(1)
np.random.seed(1)
de.config.set_seed(1)
Y
yangyongjie 已提交
52 53 54 55 56 57 58

if __name__ == '__main__':
    data_config = DataConfig()
    model_config = ModelConfig()
    train_config = TrainConfig()

    if rank_size > 1:
T
tom__chen 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        if args_opt.device_target == "Ascend":
            device_id = int(os.getenv('DEVICE_ID'))
            context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=device_id)
            context.reset_auto_parallel_context()
            context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, mirror_mean=True)
            init()
            rank_id = int(os.environ.get('RANK_ID'))
        elif args_opt.device_target == "GPU":
            init("nccl")
            context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target)
            context.reset_auto_parallel_context()
            context.set_auto_parallel_context(device_num=get_group_size(),
                                              parallel_mode=ParallelMode.DATA_PARALLEL,
                                              mirror_mean=True)
            rank_id = get_rank()
        else:
            print("Unsupported device_target ", args_opt.device_target)
            exit()
Y
yangyongjie 已提交
77
    else:
T
tom__chen 已提交
78 79
        device_id = int(os.getenv('DEVICE_ID'))
        context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=device_id)
Y
yangyongjie 已提交
80 81 82 83 84
        rank_size = None
        rank_id = None

    ds_train = create_dataset(args_opt.dataset_path,
                              train_mode=True,
85
                              epochs=1,
Y
yangyongjie 已提交
86 87 88 89 90
                              batch_size=train_config.batch_size,
                              data_type=DataType(data_config.data_format),
                              rank_size=rank_size,
                              rank_id=rank_id)

P
panfengfeng 已提交
91 92
    steps_size = ds_train.get_dataset_size()

Y
yangyongjie 已提交
93 94 95 96 97 98 99 100 101 102
    model_builder = ModelBuilder(ModelConfig, TrainConfig)
    train_net, eval_net = model_builder.get_train_eval_net()
    auc_metric = AUCMetric()
    model = Model(train_net, eval_network=eval_net, metrics={"auc": auc_metric})

    time_callback = TimeMonitor(data_size=ds_train.get_dataset_size())
    loss_callback = LossCallBack(loss_file_path=args_opt.loss_file_name)
    callback_list = [time_callback, loss_callback]

    if train_config.save_checkpoint:
T
tom__chen 已提交
103 104
        if rank_size:
            train_config.ckpt_file_name_prefix = train_config.ckpt_file_name_prefix + str(get_rank())
P
panfengfeng 已提交
105 106 107 108 109 110
        if args_opt.device_target == "GPU":
            config_ck = CheckpointConfig(save_checkpoint_steps=steps_size,
                                         keep_checkpoint_max=train_config.keep_checkpoint_max)
        else:
            config_ck = CheckpointConfig(save_checkpoint_steps=train_config.save_checkpoint_steps,
                                         keep_checkpoint_max=train_config.keep_checkpoint_max)
Y
yangyongjie 已提交
111 112 113 114 115 116 117
        ckpt_cb = ModelCheckpoint(prefix=train_config.ckpt_file_name_prefix,
                                  directory=args_opt.ckpt_path,
                                  config=config_ck)
        callback_list.append(ckpt_cb)

    if args_opt.do_eval:
        ds_eval = create_dataset(args_opt.dataset_path, train_mode=False,
118
                                 epochs=1,
Y
yangyongjie 已提交
119 120 121 122 123 124
                                 batch_size=train_config.batch_size,
                                 data_type=DataType(data_config.data_format))
        eval_callback = EvalCallBack(model, ds_eval, auc_metric,
                                     eval_file_path=args_opt.eval_file_name)
        callback_list.append(eval_callback)
    model.train(train_config.train_epochs, ds_train, callbacks=callback_list)