Beispiel #1
0
    def __init__(self):
        # path
        root_path = get_root_path()
        config_file = os.path.join(root_path,
                                   'xbot/configs/{}'.format(SlotWithBertPredictor.default_model_config))

        # load config
        config = json.load(open(config_file))
        data_path = os.path.join(root_path, config['data_dir'])
        device = config['DEVICE']

        # load intent, tag vocabulary and dataloader
        intent_vocab = json.load(open(os.path.join(data_path, 'intent_vocab.json'), encoding='utf-8'))
        tag_vocab = json.load(open(os.path.join(data_path, 'tag_vocab.json'), encoding="utf-8"))
        dataloader = Dataloader(tag_vocab=tag_vocab, intent_vocab=intent_vocab,
                                pretrained_weights=config['model']['pretrained_weights'])
        # load best model
        best_model_path = os.path.join(DEFAULT_MODEL_PATH, SlotWithBertPredictor.default_model_name)
        if not os.path.exists(best_model_path):
            download_from_url(SlotWithBertPredictor.default_model_url,
                              best_model_path)
        model = SlotWithBert(config['model'], device, dataloader.tag_dim)
        try:
            model.load_state_dict(torch.load(os.path.join(DEFAULT_MODEL_PATH,
                                                          SlotWithBertPredictor.default_model_name),
                                             map_location='cpu'))
        except Exception as e:
            print(e)
        model.to(device)

        self.model = model
        self.dataloader = dataloader
        print(f"{best_model_path} loaded - {best_model_path}")
Beispiel #2
0
    def load_config() -> dict:
        """Load config from common config and inference config from xbot/config/dst/bert .

        Returns:
            config dict
        """
        root_path = get_root_path()
        common_config_path = os.path.join(get_config_path(),
                                          BertDST.common_config_name)
        infer_config_path = os.path.join(get_config_path(),
                                         BertDST.infer_config_name)
        common_config = json.load(open(common_config_path))
        infer_config = json.load(open(infer_config_path))
        infer_config.update(common_config)
        infer_config['device'] = torch.device(
            'cuda' if torch.cuda.is_available() else 'cpu')
        infer_config['data_path'] = os.path.join(get_data_path(),
                                                 'crosswoz/dst_bert_data')
        infer_config['output_dir'] = os.path.join(root_path,
                                                  infer_config['output_dir'])
        if not os.path.exists(infer_config['data_path']):
            os.makedirs(infer_config['data_path'])
        if not os.path.exists(infer_config['output_dir']):
            os.makedirs(infer_config['output_dir'])
        return infer_config
Beispiel #3
0
    def __init__(self):
        # path
        root_path = get_root_path()

        config_file = os.path.join(get_config_path(), IntentWithBertPredictor.default_model_config)

        # load config
        config = json.load(open(config_file))
        device = config['DEVICE']

        # load intent vocabulary and dataloader
        intent_vocab = json.load(open(os.path.join(get_data_path(),
                                                   'crosswoz/nlu_intent_data/intent_vocab.json'),
                                      encoding='utf-8'))
        dataloader = Dataloader(intent_vocab=intent_vocab,
                                pretrained_weights=config['model']['pretrained_weights'])
        # load best model
        best_model_path = os.path.join(DEFAULT_MODEL_PATH, IntentWithBertPredictor.default_model_name)
        if not os.path.exists(best_model_path):
            download_from_url(IntentWithBertPredictor.default_model_url,
                              best_model_path)
        model = IntentWithBert(config['model'], device, dataloader.intent_dim)
        try:
            model.load_state_dict(torch.load(os.path.join(DEFAULT_MODEL_PATH,
                                                          IntentWithBertPredictor.default_model_name),
                                             map_location='cpu'))
        except Exception as e:
            print(e)

        # cpu process
        model.to("cpu")
        model.eval()
        self.model = model
        self.dataloader = dataloader
        print(f"{best_model_path} loaded - {best_model_path}")
Beispiel #4
0
    def __init__(self):
        root_path = get_root_path()
        config_file = os.path.join(root_path, 'xbot/configs/{}'.format(JointWithBertPredictor.default_model_config))
        config = json.load(open(config_file))
        device = config['DEVICE']
        data_dir = os.path.join(root_path, config['data_dir'])
        output_dir = os.path.join(root_path, config['output_dir'])

        intent_vocab = json.load(open(os.path.join(data_dir, 'intent_vocab.json')))
        tag_vocab = json.load(open(os.path.join(data_dir, 'tag_vocab.json')))
        dataloader = Dataloader(intent_vocab=intent_vocab, tag_vocab=tag_vocab,
                                pretrained_weights=config['model']['pretrained_weights'])

        best_model_path = os.path.join(DEFAULT_MODEL_PATH, JointWithBertPredictor.default_model_name)
        if not os.path.exists(best_model_path):
            download_from_url(JointWithBertPredictor.default_model_url,
                              best_model_path)

        model = JointWithBert(config['model'], device, dataloader.tag_dim, dataloader.intent_dim)
        try:
            model.load_state_dict(torch.load(os.path.join(DEFAULT_MODEL_PATH,
                                                          JointWithBertPredictor.default_model_name),
                                             map_location='cpu'))
        except Exception as e:
            print(e)
        model.to(device)

        self.model = model
        self.dataloader = dataloader
        print(f"{best_model_path} loaded")
Beispiel #5
0
def main():
    model_config_name = 'policy/mle/train.json'
    common_config_name = 'policy/mle/common.json'

    data_urls = {
        'sys_da_voc.json': 'http://qiw2jpwfc.hn-bkt.clouddn.com/usr_da_voc.json',
        'usr_da_voc.json': 'http://qiw2jpwfc.hn-bkt.clouddn.com/usr_da_voc.json'
    }

    # load config
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    model_config_path = os.path.join(get_config_path(), model_config_name)
    common_config = json.load(open(common_config_path))
    model_config = json.load(open(model_config_path))
    model_config.update(common_config)

    model_config['n_gpus'] = torch.cuda.device_count()
    model_config['batch_size'] = max(1, model_config['n_gpus']) * model_config['batch_size']
    model_config['device'] = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')

    model_config['data_path'] = os.path.join(get_data_path(), 'crosswoz/policy_mle_data')
    model_config['raw_data_path'] = os.path.join(get_data_path(), 'crosswoz/raw')
    model_config['output_dir'] = os.path.join(root_path, model_config['output_dir'])
    if model_config['load_model_name']:
        model_config['model_path'] = os.path.join(model_config['output_dir'], model_config['load_model_name'])
    else:
        model_config['model_path'] = ''
    if not os.path.exists(model_config['data_path']):
        os.makedirs(model_config['data_path'])
    if not os.path.exists(model_config['output_dir']):
        os.makedirs(model_config['output_dir'])

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(model_config['data_path'], data_key)
        file_name = data_key.split('.')[0]
        model_config[file_name] = dst
        if not os.path.exists(dst):
            download_from_url(url, dst)

    print(f'>>> Train configs:')
    print('\t', model_config)

    set_seed(model_config['random_seed'])

    agent = Trainer(model_config)

    # 训练
    if model_config['do_train']:
        start_epoch = 0 if not model_config['model_path'] else int(model_config['model_path'].split('-')[2]) + 1
        best = float('inf')
        for epoch in tqdm(range(start_epoch, model_config['num_epochs']), desc='Epoch'):
            agent.imitating(epoch)
            best = agent.imit_eval(epoch, best)

    agent.calc_metrics()
Beispiel #6
0
def main():
    model_config_name = 'dst/bert/train.json'
    common_config_name = 'dst/bert/common.json'

    data_urls = {
        'train4bert_dst.json': 'http://xbot.bslience.cn/train4bert_dst.json',
        'dev4bert_dst.json': 'http://xbot.bslience.cn/dev4bert_dst.json',
        'test4bert_dst.json': 'http://xbot.bslience.cn/test4bert_dst.json',
        'cleaned_ontology.json':
        'http://xbot.bslience.cn/cleaned_ontology.json',
        'config.json': 'http://xbot.bslience.cn/bert-base-chinese/config.json',
        'pytorch_model.bin':
        'http://xbot.bslience.cn/bert-base-chinese/pytorch_model.bin',
        'vocab.txt': 'http://xbot.bslience.cn/bert-base-chinese/vocab.txt'
    }

    # load config
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    train_config_path = os.path.join(get_config_path(), model_config_name)
    common_config = json.load(open(common_config_path))
    train_config = json.load(open(train_config_path))
    train_config.update(common_config)
    train_config['n_gpus'] = torch.cuda.device_count()
    train_config['train_batch_size'] = max(
        1, train_config['n_gpus']) * train_config['train_batch_size']
    train_config['device'] = torch.device(
        'cuda' if torch.cuda.is_available() else 'cpu')

    train_config['data_path'] = os.path.join(get_data_path(),
                                             'crosswoz/dst_bert_data')
    train_config['output_dir'] = os.path.join(root_path,
                                              train_config['output_dir'])
    if not os.path.exists(train_config['data_path']):
        os.makedirs(train_config['data_path'])
    if not os.path.exists(train_config['output_dir']):
        os.makedirs(train_config['output_dir'])

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(train_config['data_path'], data_key)
        file_name = data_key.split('.')[0]
        train_config[file_name] = dst
        if not os.path.exists(dst):
            download_from_url(url, dst)

    # train
    trainer = Trainer(train_config)
    trainer.train()
    trainer.eval_test()
    get_recall(train_config['data_path'])
Beispiel #7
0
def main():
    model_config_name = "dst/bert/train.json"
    common_config_name = "dst/bert/common.json"

    data_urls = {
        "train4bert_dst.json": "http://xbot.bslience.cn/train4bert_dst.json",
        "dev4bert_dst.json": "http://xbot.bslience.cn/dev4bert_dst.json",
        "test4bert_dst.json": "http://xbot.bslience.cn/test4bert_dst.json",
        "cleaned_ontology.json": "http://xbot.bslience.cn/cleaned_ontology.json",
        "config.json": "http://xbot.bslience.cn/bert-base-chinese/config.json",
        "pytorch_model.bin": "http://xbot.bslience.cn/bert-base-chinese/pytorch_model.bin",
        "vocab.txt": "http://xbot.bslience.cn/bert-base-chinese/vocab.txt",
    }

    # load config
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    train_config_path = os.path.join(get_config_path(), model_config_name)
    common_config = json.load(open(common_config_path))
    train_config = json.load(open(train_config_path))
    train_config.update(common_config)
    train_config["n_gpus"] = torch.cuda.device_count()
    train_config["train_batch_size"] = (
        max(1, train_config["n_gpus"]) * train_config["train_batch_size"]
    )
    train_config["device"] = torch.device(
        "cuda" if torch.cuda.is_available() else "cpu"
    )

    train_config["data_path"] = os.path.join(get_data_path(), "crosswoz/dst_bert_data")
    train_config["output_dir"] = os.path.join(root_path, train_config["output_dir"])
    if not os.path.exists(train_config["data_path"]):
        os.makedirs(train_config["data_path"])
    if not os.path.exists(train_config["output_dir"]):
        os.makedirs(train_config["output_dir"])

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(train_config["data_path"], data_key)
        file_name = data_key.split(".")[0]
        train_config[file_name] = dst
        if not os.path.exists(dst):
            download_from_url(url, dst)

    # train
    trainer = Trainer(train_config)
    trainer.train()
    trainer.eval_test()
    get_recall(train_config["data_path"])
Beispiel #8
0
def update_config(common_config_name, train_config_name, task_path):
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    train_config_path = os.path.join(get_config_path(), train_config_name)
    common_config = json.load(open(common_config_path))
    train_config = json.load(open(train_config_path))
    train_config.update(common_config)
    train_config["n_gpus"] = torch.cuda.device_count()
    train_config["train_batch_size"] = (max(1, train_config["n_gpus"]) *
                                        train_config["train_batch_size"])
    train_config["device"] = torch.device(
        "cuda" if torch.cuda.is_available() else "cpu")
    train_config["data_path"] = os.path.join(get_data_path(), task_path)
    train_config["output_dir"] = os.path.join(root_path,
                                              train_config["output_dir"])
    if not os.path.exists(train_config["data_path"]):
        os.makedirs(train_config["data_path"])
    if not os.path.exists(train_config["output_dir"]):
        os.makedirs(train_config["output_dir"])
    return train_config
Beispiel #9
0
    def __init__(self):
        # path
        root_path = get_root_path()

        config_file = os.path.join(
            get_config_path(), IntentWithBertPredictor.default_model_config)

        # load config
        config = json.load(open(config_file))
        self.device = config["DEVICE"]

        # load intent vocabulary and dataloader
        intent_vocab = json.load(
            open(
                os.path.join(get_data_path(),
                             "crosswoz/nlu_intent_data/intent_vocab.json"),
                encoding="utf-8",
            ))
        dataloader = Dataloader(
            intent_vocab=intent_vocab,
            pretrained_weights=config["model"]["pretrained_weights"],
        )
        # load best model
        best_model_path = os.path.join(
            os.path.join(root_path, DEFAULT_MODEL_PATH),
            IntentWithBertPredictor.default_model_name,
        )
        # best_model_path = os.path.join(DEFAULT_MODEL_PATH, IntentWithBertPredictor.default_model_name)
        if not os.path.exists(best_model_path):
            download_from_url(IntentWithBertPredictor.default_model_url,
                              best_model_path)
        model = IntentWithBert(config["model"], self.device,
                               dataloader.intent_dim)
        model.load_state_dict(
            torch.load(best_model_path, map_location=self.device))

        model.to(self.device)
        model.eval()
        self.model = model
        self.dataloader = dataloader
        print(f"{best_model_path} loaded - {best_model_path}")
Beispiel #10
0
    def load_config() -> dict:
        """Load config from common config and inference config from src/xbot/config/dst/bert .

        Returns:
            config dict
        """
        root_path = get_root_path()
        common_config_path = os.path.join(get_config_path(), BertDST.common_config_name)
        infer_config_path = os.path.join(get_config_path(), BertDST.infer_config_name)
        common_config = json.load(open(common_config_path))
        infer_config = json.load(open(infer_config_path))
        infer_config.update(common_config)
        infer_config["device"] = torch.device(
            "cuda" if torch.cuda.is_available() else "cpu"
        )
        infer_config["data_path"] = os.path.join(
            get_data_path(), "crosswoz/dst_bert_data"
        )
        infer_config["output_dir"] = os.path.join(root_path, infer_config["output_dir"])
        if not os.path.exists(infer_config["data_path"]):
            os.makedirs(infer_config["data_path"])
        if not os.path.exists(infer_config["output_dir"]):
            os.makedirs(infer_config["output_dir"])
        return infer_config
Beispiel #11
0
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)


if __name__ == '__main__':
    data_urls = {
        'intent_train_data.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/intent_train_data.json',
        'intent_val_data.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/intent_val_data.json',
        'intent_test_data.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/intent_test_data.json'
    }
    # load config
    root_path = get_root_path()
    config_path = os.path.join(get_config_path(),
                               'crosswoz_all_context_nlu_intent.json')
    config = json.load(open(config_path))
    data_path = os.path.join(get_data_path(), 'crosswoz/nlu_intent_data/')
    output_dir = config['output_dir']
    output_dir = os.path.join(root_path, output_dir)
    log_dir = config['log_dir']
    log_dir = os.path.join(root_path, log_dir)
    device = config['DEVICE']

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(os.path.join(data_path, data_key))
        if not os.path.exists(dst):
            download_from_url(url, dst)
Beispiel #12
0
import sys
import json
import pickle

import numpy as np

import torch
import torch.nn as nn

from xbot.util.dst_util import DST
from xbot.util.state import default_state
from xbot.util.download import download_from_url
from xbot.util.path import get_data_path, get_config_path, get_root_path
from data.crosswoz.data_process.dst.trade_preprocess import get_slot_information, prepare_data_for_update

sys.path.append(os.path.join(get_root_path(), 'script/dst/trade'))


class EncoderRNN(nn.Module):
    def __init__(self, vocab_size, hidden_size, dropout, n_layers, pad_id,
                 pretrained_embedding_path='', load_embedding=False, fix_embedding=True):
        super(EncoderRNN, self).__init__()
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.dropout = dropout
        self.dropout_layer = nn.Dropout(dropout)
        self.embedding = nn.Embedding(vocab_size, hidden_size, padding_idx=pad_id)
        self.embedding.weight.data.normal_(0, 0.1)
        self.gru = nn.GRU(hidden_size, hidden_size, n_layers,
                          dropout=dropout, bidirectional=True)
Beispiel #13
0
def main():
    model_config_name = 'dst/trade/train.json'
    common_config_name = 'dst/trade/common.json'

    data_urls = {
        'train_dials.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/train_dials.json',
        'dev_dials.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/dev_dials.json',
        'test_dials.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/test_dials.json',
        'ontology.json':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/ontology.json',
        'sgns.wiki.bigram.bz2':
        'http://qiw2jpwfc.hn-bkt.clouddn.com/sgns.wiki.bigram.bz2'
    }

    # load config
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    model_config_path = os.path.join(get_config_path(), model_config_name)
    common_config = json.load(open(common_config_path))
    model_config = json.load(open(model_config_path))
    model_config.update(common_config)
    model_config['n_gpus'] = torch.cuda.device_count()
    model_config['batch_size'] = max(
        1, model_config['n_gpus']) * model_config['batch_size']
    model_config['device'] = torch.device(
        'cuda:0' if torch.cuda.is_available() else 'cpu')
    if model_config['load_embedding']:
        model_config['hidden_size'] = 300

    model_config['data_path'] = os.path.join(get_data_path(),
                                             'crosswoz/dst_trade_data')
    model_config['output_dir'] = os.path.join(
        root_path, model_config['output_dir'])  # 可以用来保存模型文件
    if model_config['load_model_name']:
        model_config['model_path'] = os.path.join(
            model_config['output_dir'], model_config['load_model_name'])
    else:
        model_config['model_path'] = ''
    if not os.path.exists(model_config['data_path']):
        os.makedirs(model_config['data_path'])
    if not os.path.exists(model_config['output_dir']):
        os.makedirs(model_config['output_dir'])

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(model_config['data_path'], data_key)
        if '_' in data_key:
            file_name = data_key.split('.')[0]
        elif 'wiki.bigram' in data_key:
            file_name = 'orig_pretrained_embedding'
        else:
            file_name = data_key.split('.')[0]  # ontology
        model_config[file_name] = dst
        if not os.path.exists(dst):
            download_from_url(url, dst)

    avg_best, cnt, acc = 0.0, 0, 0.0

    # 数据预处理
    train, dev, test, langs, slots, gating_dict = prepare_data_seq(
        model_config)
    lang = langs[0]
    model_config['pretrained_embedding_path'] = os.path.join(
        model_config['data_path'], f'emb{len(lang.index2word)}')

    print(f'>>> Train configs:')
    print('\t', model_config)

    # 初始化训练
    trainer = Trainer(config=model_config,
                      langs=langs,
                      gating_dict=gating_dict,
                      slots=slots)

    # 训练
    start_epoch = 0 if not model_config['model_path'] else int(
        model_config['model_path'].split('-')[2]) + 1

    for epoch in tqdm(range(start_epoch, model_config['num_epochs']),
                      desc='Epoch'):
        progress_bar = tqdm(enumerate(train), total=len(train))

        for i, data in progress_bar:
            trainer.train_batch(data, slots, reset=(i == 0))
            trainer.optimize(int(model_config['grad_clip']))
            progress_bar.set_description(trainer.print_loss())

        if (epoch + 1) % int(model_config['eval_steps']) == 0:

            acc = trainer.evaluate(dev, avg_best, slots, epoch,
                                   model_config['early_stop'])
            trainer.scheduler.step(acc)

            if acc >= avg_best:
                avg_best = acc
                cnt = 0
            else:
                cnt += 1

            if cnt == model_config["patience"] or (
                    acc == 1.0 and model_config['early_stop'] is None):
                print("Ran out of patient, early stop...")
                break
Beispiel #14
0
def main():
    model_config_name = "policy/mle/train.json"
    common_config_name = "policy/mle/common.json"

    data_urls = {
        "sys_da_voc.json":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/usr_da_voc.json",
        "usr_da_voc.json":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/usr_da_voc.json",
    }

    # load config
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    model_config_path = os.path.join(get_config_path(), model_config_name)
    common_config = json.load(open(common_config_path))
    model_config = json.load(open(model_config_path))
    model_config.update(common_config)

    model_config["n_gpus"] = torch.cuda.device_count()
    model_config["batch_size"] = (max(1, model_config["n_gpus"]) *
                                  model_config["batch_size"])
    model_config["device"] = torch.device(
        "cuda:0" if torch.cuda.is_available() else "cpu")

    model_config["data_path"] = os.path.join(get_data_path(),
                                             "crosswoz/policy_mle_data")
    model_config["raw_data_path"] = os.path.join(get_data_path(),
                                                 "crosswoz/raw")
    model_config["output_dir"] = os.path.join(root_path,
                                              model_config["output_dir"])
    if model_config["load_model_name"]:
        model_config["model_path"] = os.path.join(
            model_config["output_dir"], model_config["load_model_name"])
    else:
        model_config["model_path"] = ""
    if not os.path.exists(model_config["data_path"]):
        os.makedirs(model_config["data_path"])
    if not os.path.exists(model_config["output_dir"]):
        os.makedirs(model_config["output_dir"])

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(model_config["data_path"], data_key)
        file_name = data_key.split(".")[0]
        model_config[file_name] = dst
        if not os.path.exists(dst):
            download_from_url(url, dst)

    print(f">>> Train configs:")
    print("\t", model_config)

    set_seed(model_config["random_seed"])

    agent = Trainer(model_config)

    # 训练
    if model_config["do_train"]:
        start_epoch = (0 if not model_config["model_path"] else
                       int(model_config["model_path"].split("-")[2]) + 1)
        best = float("inf")
        for epoch in tqdm(range(start_epoch, model_config["num_epochs"]),
                          desc="Epoch"):
            agent.imitating(epoch)
            best = agent.imit_eval(epoch, best)

    agent.calc_metrics()
Beispiel #15
0
def main():
    model_config_name = "dst/trade/train.json"
    common_config_name = "dst/trade/common.json"

    data_urls = {
        "train_dials.json":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/train_dials.json",
        "dev_dials.json":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/dev_dials.json",
        "test_dials.json":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/test_dials.json",
        "ontology.json":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/ontology.json",
        "sgns.wiki.bigram.bz2":
        "http://qiw2jpwfc.hn-bkt.clouddn.com/sgns.wiki.bigram.bz2",
    }

    # load config
    root_path = get_root_path()
    common_config_path = os.path.join(get_config_path(), common_config_name)
    model_config_path = os.path.join(get_config_path(), model_config_name)
    common_config = json.load(open(common_config_path))
    model_config = json.load(open(model_config_path))
    model_config.update(common_config)
    model_config["n_gpus"] = torch.cuda.device_count()
    model_config["batch_size"] = (max(1, model_config["n_gpus"]) *
                                  model_config["batch_size"])
    model_config["device"] = torch.device(
        "cuda:0" if torch.cuda.is_available() else "cpu")
    if model_config["load_embedding"]:
        model_config["hidden_size"] = 300

    model_config["data_path"] = os.path.join(get_data_path(),
                                             "crosswoz/dst_trade_data")
    model_config["output_dir"] = os.path.join(
        root_path, model_config["output_dir"])  # 可以用来保存模型文件
    if model_config["load_model_name"]:
        model_config["model_path"] = os.path.join(
            model_config["output_dir"], model_config["load_model_name"])
    else:
        model_config["model_path"] = ""
    if not os.path.exists(model_config["data_path"]):
        os.makedirs(model_config["data_path"])
    if not os.path.exists(model_config["output_dir"]):
        os.makedirs(model_config["output_dir"])

    # download data
    for data_key, url in data_urls.items():
        dst = os.path.join(model_config["data_path"], data_key)
        if "_" in data_key:
            file_name = data_key.split(".")[0]
        elif "wiki.bigram" in data_key:
            file_name = "orig_pretrained_embedding"
        else:
            file_name = data_key.split(".")[0]  # ontology
        model_config[file_name] = dst
        if not os.path.exists(dst):
            download_from_url(url, dst)

    avg_best, cnt, acc = 0.0, 0, 0.0

    # 数据预处理
    train, dev, test, langs, slots, gating_dict = prepare_data_seq(
        model_config)
    lang = langs[0]
    model_config["pretrained_embedding_path"] = os.path.join(
        model_config["data_path"], f"emb{len(lang.index2word)}")

    print(f">>> Train configs:")
    print("\t", model_config)

    # 初始化训练
    trainer = Trainer(config=model_config,
                      langs=langs,
                      gating_dict=gating_dict,
                      slots=slots)

    # 训练
    start_epoch = (0 if not model_config["model_path"] else
                   int(model_config["model_path"].split("-")[2]) + 1)

    for epoch in tqdm(range(start_epoch, model_config["num_epochs"]),
                      desc="Epoch"):
        progress_bar = tqdm(enumerate(train), total=len(train))

        for i, data in progress_bar:
            trainer.train_batch(data, slots, reset=(i == 0))
            trainer.optimize(int(model_config["grad_clip"]))
            progress_bar.set_description(trainer.print_loss())

        if (epoch + 1) % int(model_config["eval_steps"]) == 0:

            acc = trainer.evaluate(dev, avg_best, slots, epoch,
                                   model_config["early_stop"])
            trainer.scheduler.step(acc)

            if acc >= avg_best:
                avg_best = acc
                cnt = 0
            else:
                cnt += 1

            if cnt == model_config["patience"] or (
                    acc == 1.0 and model_config["early_stop"] is None):
                print("Ran out of patient, early stop...")
                break