train.py 5.3 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 22

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

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')
parser.add_argument('--eval_file_name', type=str, default="./auc.log", help='eval file path')
parser.add_argument('--loss_file_name', type=str, default="./loss.log", help='loss file path')
parser.add_argument('--do_eval', type=bool, default=True, help='Do evaluation or not.')
T
tom__chen 已提交
40
parser.add_argument('--device_target', type=str, default="Ascend", help='Ascend, GPU, or CPU')
Y
yangyongjie 已提交
41
args_opt, _ = parser.parse_known_args()
T
tom__chen 已提交
42
rank_size = int(os.environ.get("RANK_SIZE", 1))
Y
yangyongjie 已提交
43

T
tom__chen 已提交
44 45 46
random.seed(1)
np.random.seed(1)
de.config.set_seed(1)
Y
yangyongjie 已提交
47 48 49 50 51 52 53

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

    if rank_size > 1:
T
tom__chen 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        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 已提交
72
    else:
T
tom__chen 已提交
73 74
        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 已提交
75 76 77 78 79
        rank_size = None
        rank_id = None

    ds_train = create_dataset(args_opt.dataset_path,
                              train_mode=True,
80
                              epochs=1,
Y
yangyongjie 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
                              batch_size=train_config.batch_size,
                              data_type=DataType(data_config.data_format),
                              rank_size=rank_size,
                              rank_id=rank_id)

    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 已提交
96 97
        if rank_size:
            train_config.ckpt_file_name_prefix = train_config.ckpt_file_name_prefix + str(get_rank())
Y
yangyongjie 已提交
98 99 100 101 102 103 104 105 106
        config_ck = CheckpointConfig(save_checkpoint_steps=train_config.save_checkpoint_steps,
                                     keep_checkpoint_max=train_config.keep_checkpoint_max)
        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,
107
                                 epochs=1,
Y
yangyongjie 已提交
108 109 110 111 112 113
                                 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)