link_prediction.py 6.3 KB
Newer Older
Z
Zeyu Chen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# 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.

import os
import io
import random
import time
Z
Zhong Hui 已提交
19 20
import argparse
from functools import partial
Z
Zeyu Chen 已提交
21

Z
Zhong Hui 已提交
22 23
import numpy as np
import yaml
Z
Zeyu Chen 已提交
24
import paddle
Z
Zhong Hui 已提交
25 26 27
import pgl
from easydict import EasyDict as edict
from paddlenlp.utils.log import logger
Z
Zeyu Chen 已提交
28 29

from models import ErnieSageForLinkPrediction
Z
Zhong Hui 已提交
30
from data import TrainData, PredictData, GraphDataLoader, batch_fn
Z
Zeyu Chen 已提交
31 32 33 34 35 36 37 38


def set_seed(config):
    random.seed(config.seed)
    np.random.seed(config.seed)
    paddle.seed(config.seed)


Z
Zhong Hui 已提交
39 40 41 42 43 44 45
def load_data(graph_data_path):
    base_graph = pgl.Graph.load(graph_data_path)
    term_ids = np.load(
        os.path.join(graph_data_path, "term_ids.npy"), mmap_mode="r")
    return base_graph, term_ids


Z
Zeyu Chen 已提交
46 47 48 49 50 51
def do_train(config):
    paddle.set_device("gpu" if config.n_gpu else "cpu")
    if paddle.distributed.get_world_size() > 1:
        paddle.distributed.init_parallel_env()
    set_seed(config)

Z
Zhong Hui 已提交
52 53 54 55 56 57 58
    base_graph, term_ids = load_data(config.graph_work_path)
    collate_fn = partial(
        batch_fn,
        samples=config.samples,
        base_graph=base_graph,
        term_ids=term_ids)

Z
Zeyu Chen 已提交
59
    mode = 'train'
Z
Zhong Hui 已提交
60
    train_ds = TrainData(config.graph_work_path)
Z
Zeyu Chen 已提交
61 62 63 64
    model = ErnieSageForLinkPrediction.from_pretrained(
        config.model_name_or_path, config=config)
    model = paddle.DataParallel(model)

Z
Zhong Hui 已提交
65 66 67 68 69 70
    train_loader = GraphDataLoader(
        train_ds,
        batch_size=config.batch_size,
        shuffle=True,
        num_workers=config.sample_workers,
        collate_fn=collate_fn)
Z
Zeyu Chen 已提交
71 72 73 74 75 76 77

    optimizer = paddle.optimizer.Adam(
        learning_rate=config.lr, parameters=model.parameters())

    global_step = 0
    tic_train = time.time()
    for epoch in range(config.epoch):
Z
Zhong Hui 已提交
78
        for step, (graphs, datas) in enumerate(train_loader):
Z
Zeyu Chen 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
            global_step += 1
            loss, outputs = model(graphs, datas)
            if global_step % config.log_per_step == 0:
                logger.info(
                    "global step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s"
                    % (global_step, epoch, step, loss,
                       config.log_per_step / (time.time() - tic_train)))
                tic_train = time.time()
            loss.backward()
            optimizer.step()
            optimizer.clear_gradients()
            if global_step % config.save_per_step == 0:
                if (not config.n_gpu > 1) or paddle.distributed.get_rank() == 0:
                    output_dir = os.path.join(config.output_path,
                                              "model_%d" % global_step)
                    if not os.path.exists(output_dir):
                        os.makedirs(output_dir)
                    model._layers.save_pretrained(output_dir)
Z
Zhong Hui 已提交
97 98 99 100 101
    if (not config.n_gpu > 1) or paddle.distributed.get_rank() == 0:
        output_dir = os.path.join(config.output_path, "last")
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        model._layers.save_pretrained(output_dir)
Z
Zeyu Chen 已提交
102 103 104 105 106 107


def tostr(data_array):
    return " ".join(["%.5lf" % d for d in data_array])


Z
Zhong Hui 已提交
108
@paddle.no_grad()
Z
Zeyu Chen 已提交
109 110 111 112 113 114 115 116 117
def do_predict(config):
    paddle.set_device("gpu" if config.n_gpu else "cpu")
    if paddle.distributed.get_world_size() > 1:
        paddle.distributed.init_parallel_env()
    set_seed(config)

    mode = 'predict'
    num_nodes = int(
        np.load(os.path.join(config.graph_work_path, "num_nodes.npy")))
Z
Zhong Hui 已提交
118 119 120 121 122 123 124 125

    base_graph, term_ids = load_data(config.graph_work_path)
    collate_fn = partial(
        batch_fn,
        samples=config.samples,
        base_graph=base_graph,
        term_ids=term_ids)

Z
Zeyu Chen 已提交
126
    model = ErnieSageForLinkPrediction.from_pretrained(
Z
Zhong Hui 已提交
127 128
        config.infer_model, config=config)

Z
Zeyu Chen 已提交
129
    model = paddle.DataParallel(model)
Z
Zhong Hui 已提交
130
    predict_ds = PredictData(num_nodes)
Z
Zeyu Chen 已提交
131

Z
Zhong Hui 已提交
132 133 134 135 136 137
    predict_loader = GraphDataLoader(
        predict_ds,
        batch_size=config.infer_batch_size,
        shuffle=True,
        num_workers=config.sample_workers,
        collate_fn=collate_fn)
Z
Zeyu Chen 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150

    trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
    id2str = io.open(
        os.path.join(config.graph_work_path, "terms.txt"),
        encoding=config.encoding).readlines()
    if not os.path.exists(config.output_path):
        os.mkdir(config.output_path)
    fout = io.open(
        "%s/part-%s" % (config.output_path, trainer_id), "w", encoding="utf8")

    global_step = 0
    epoch = 0
    tic_train = time.time()
Z
Zhong Hui 已提交
151 152
    model.eval()
    for step, (graphs, datas) in enumerate(predict_loader):
Z
Zeyu Chen 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        global_step += 1
        loss, outputs = model(graphs, datas)
        for user_feat, user_real_index in zip(outputs[0].numpy(),
                                              outputs[3].numpy()):
            sri = id2str[int(user_real_index)].strip("\n")
            line = "{}\t{}\n".format(sri, tostr(user_feat))
            fout.write(line)
        if global_step % config.log_per_step == 0:
            logger.info(
                "predict step %d, epoch: %d, batch: %d, loss: %f, speed: %.2f step/s"
                % (global_step, epoch, step, loss,
                   config.log_per_step / (time.time() - tic_train)))
            tic_train = time.time()
    fout.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='main')
    parser.add_argument("--conf", type=str, default="./config.yaml")
    parser.add_argument("--do_predict", action='store_true', default=False)
    args = parser.parse_args()
    config = edict(yaml.load(open(args.conf), Loader=yaml.FullLoader))
    logger.info(config)
    if args.do_predict:
        do_func = do_predict
    else:
        do_func = do_train

    if config.n_gpu > 1 and paddle.fluid.core.is_compiled_with_cuda(
    ) and paddle.fluid.core.get_cuda_device_count() > 1:
        paddle.distributed.spawn(do_func, args=(config, ), nprocs=config.n_gpu)
    else:
        do_func(config)