run_classifier.py 18.0 KB
Newer Older
王肖 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
#   Copyright (c) 2019 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.
"""
SimNet Task
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import time
import argparse
import multiprocessing
import sys

defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)

sys.path.append("..")

import paddle
import paddle.fluid as fluid
import numpy as np
import config
import utils
import reader
import nets.paddle_layers as layers
import io
import logging

from utils import ArgConfig
from model_check import check_version
from model_check import check_cuda

            
def train(conf_dict, args):
    """
    train process
    """
    
    # Get device
    if args.use_cuda:
        place = fluid.CUDAPlace(0)
    else:
        place = fluid.CPUPlace()
    
    # run train
    logging.info("start train process ...")

    def valid_and_test(pred_list, process, mode):
        """
        return auc and acc
        """
        pred_list = np.vstack(pred_list)
        if mode == "test":
            label_list = process.get_test_label()
        elif mode == "valid":
            label_list = process.get_valid_label()
        if args.task_mode == "pairwise":
            pred_list = (pred_list + 1) / 2
            pred_list = np.hstack(
                (np.ones_like(pred_list) - pred_list, pred_list))
        metric.reset()
        metric.update(pred_list, label_list)
        auc = metric.eval()
        if args.compute_accuracy:
            acc = utils.get_accuracy(pred_list, label_list, args.task_mode,
                                     args.lamda)
            return auc, acc
        else:
            return auc
    

    with fluid.dygraph.guard(place):
        # used for continuous evaluation 
        if args.enable_ce:
            SEED = 102
            fluid.default_startup_program().random_seed = SEED
            fluid.default_main_program().random_seed = SEED

        # loading vocabulary
        vocab = utils.load_vocab(args.vocab_path)
        # get vocab size
        conf_dict['dict_size'] = len(vocab)
        # Load network structure dynamically
        net = utils.import_class("./nets",
                                conf_dict["net"]["module_name"],
                                conf_dict["net"]["class_name"])(conf_dict)
        if args.init_checkpoint is not "":
            model, _ = fluid.dygraph.load_dygraph(args.init_checkpoint)
            net.set_dict(model)
        # Load loss function dynamically
        loss = utils.import_class("./nets/losses",
                                conf_dict["loss"]["module_name"],
                                conf_dict["loss"]["class_name"])(conf_dict)
        # Load Optimization method
        learning_rate = conf_dict["optimizer"]["learning_rate"]
        optimizer_name = conf_dict["optimizer"]["class_name"]
        if optimizer_name=='SGDOptimizer':
            optimizer = fluid.optimizer.SGDOptimizer(learning_rate,parameter_list=net.parameters())
        elif optimizer_name=='AdamOptimizer':
            beta1 = conf_dict["optimizer"]["beta1"]
            beta2 = conf_dict["optimizer"]["beta2"]
            epsilon = conf_dict["optimizer"]["epsilon"]
            optimizer = fluid.optimizer.AdamOptimizer(
            learning_rate,
            beta1=beta1,
            beta2=beta2,
            epsilon=epsilon,
            parameter_list=net.parameters())

        # load auc method
        metric = fluid.metrics.Auc(name="auc")
        simnet_process = reader.SimNetProcessor(args, vocab) 

        # set global step
        global_step = 0
        ce_info = []
        losses = []
        start_time = time.time()

        train_pyreader = fluid.io.PyReader(capacity=16, return_list=True, use_double_buffer=False)
        get_train_examples = simnet_process.get_reader("train",epoch=args.epoch)
        train_pyreader.decorate_sample_list_generator(
                paddle.batch(get_train_examples, batch_size=args.batch_size),
                place)
        if args.do_valid:
            valid_pyreader = fluid.io.PyReader(capacity=16, return_list=True, use_double_buffer=False)
            get_valid_examples = simnet_process.get_reader("valid")  
            valid_pyreader.decorate_sample_list_generator(
                paddle.batch(get_valid_examples, batch_size=args.batch_size),
                place)
            pred_list = []

        if args.task_mode == "pairwise":
         
            for left, pos_right, neg_right in train_pyreader():
                
                left = fluid.layers.reshape(left, shape=[-1, 1])
                pos_right = fluid.layers.reshape(pos_right, shape=[-1, 1])
                neg_right = fluid.layers.reshape(neg_right, shape=[-1, 1])
                net.train()
                global_step += 1
                left_feat, pos_score = net(left, pos_right)
                pred = pos_score
                _, neg_score = net(left, neg_right)
                avg_cost = loss.compute(pos_score, neg_score)
                losses.append(np.mean(avg_cost.numpy()))  
                avg_cost.backward()
                optimizer.minimize(avg_cost)
                net.clear_gradients()
                
                if args.do_valid and global_step % args.validation_steps == 0:
                    for left, pos_right in valid_pyreader():
                        left = fluid.layers.reshape(left, shape=[-1, 1])
                        pos_right = fluid.layers.reshape(pos_right, shape=[-1, 1])
                        net.eval()
                        left_feat, pos_score = net(left, pos_right)
                        pred = pos_score
                       
                        pred_list += list(pred.numpy())  
                    valid_result = valid_and_test(pred_list, simnet_process, "valid")     
                    if args.compute_accuracy:
                        valid_auc, valid_acc = valid_result
                        logging.info(
                            "global_steps: %d, valid_auc: %f, valid_acc: %f, valid_loss: %f" %
                            (global_step, valid_auc, valid_acc, np.mean(losses)))
                    else:
                        valid_auc = valid_result
                        logging.info("global_steps: %d, valid_auc: %f, valid_loss: %f" %
                                    (global_step, valid_auc, np.mean(losses)))

                if global_step % args.save_steps == 0:
                    model_save_dir = os.path.join(args.output_dir,
                                                conf_dict["model_path"])
                    model_path = os.path.join(model_save_dir, str(global_step))
                        
                    if not os.path.exists(model_save_dir):
                        os.makedirs(model_save_dir)
                    fluid.dygraph.save_dygraph(net.state_dict(), model_path)
                    
                    logging.info("saving infer model in %s" % model_path)
        else:
            for left, right, label in train_pyreader():
                left = fluid.layers.reshape(left, shape=[-1, 1])
                right = fluid.layers.reshape(right, shape=[-1, 1])
                label = fluid.layers.reshape(label, shape=[-1, 1])
                net.train()
                global_step += 1 
                left_feat, pred = net(left, right)
                avg_cost = loss.compute(pred, label)
                losses.append(np.mean(avg_cost.numpy())) 
                avg_cost.backward()
                optimizer.minimize(avg_cost)
                net.clear_gradients()
            
                if args.do_valid and global_step % args.validation_steps == 0:
                    for left, right in valid_pyreader():
                        left = fluid.layers.reshape(left, shape=[-1, 1])
                        right = fluid.layers.reshape(right, shape=[-1, 1])
                        net.eval()
                        left_feat, pred = net(left, right)
                        pred_list += list(pred.numpy())
                    valid_result = valid_and_test(pred_list, simnet_process, "valid")     
                    if args.compute_accuracy:
                        valid_auc, valid_acc = valid_result
                        logging.info(
                            "global_steps: %d, valid_auc: %f, valid_acc: %f, valid_loss: %f" %
                            (global_step, valid_auc, valid_acc, np.mean(losses)))
                    else:
                        valid_auc = valid_result
                        logging.info("global_steps: %d, valid_auc: %f, valid_loss: %f" %
                                    (global_step, valid_auc, np.mean(losses)))

                if global_step % args.save_steps == 0:
                    model_save_dir = os.path.join(args.output_dir,
                                                conf_dict["model_path"])
                    model_path = os.path.join(model_save_dir, str(global_step))
                        
                    if not os.path.exists(model_save_dir):
                        os.makedirs(model_save_dir)
                    fluid.dygraph.save_dygraph(net.state_dict(), model_path)
                    
                    logging.info("saving infer model in %s" % model_path)

        end_time = time.time()     
        ce_info.append([np.mean(losses), end_time - start_time])
        # final save
        logging.info("the final step is %s" % global_step)    
        model_save_dir = os.path.join(args.output_dir,
                                    conf_dict["model_path"])
        model_path = os.path.join(model_save_dir, str(global_step))
        
        if not os.path.exists(model_save_dir):
            os.makedirs(model_save_dir)
        fluid.dygraph.save_dygraph(net.state_dict(), model_path)
        logging.info("saving infer model in %s" % model_path)
        # used for continuous evaluation
        if args.enable_ce:
        # if True:
            card_num = get_cards()
            ce_loss = 0
            ce_time = 0
            try:
                ce_loss = ce_info[-1][0]
                ce_time = ce_info[-1][1]
            except:
                logging.info("ce info err!")
            print("kpis\teach_step_duration_%s_card%s\t%s" %
                (args.task_name, card_num, ce_time))
            print("kpis\ttrain_loss_%s_card%s\t%f" %
                (args.task_name, card_num, ce_loss))

        if args.do_test:
            # Get Feeder and Reader
            test_pyreader = fluid.io.PyReader(capacity=16, return_list=True, use_double_buffer=False)
            get_test_examples = simnet_process.get_reader("test")
            test_pyreader.decorate_sample_list_generator(
                paddle.batch(get_test_examples, batch_size=args.batch_size),
                place)
            pred_list = []
            for left, pos_right in test_pyreader():
                left = fluid.layers.reshape(left, shape=[-1, 1])
                pos_right = fluid.layers.reshape(pos_right, shape=[-1, 1])
                net.eval()
                left = fluid.layers.reshape(left, shape=[-1, 1])
                pos_right = fluid.layers.reshape(pos_right, shape=[-1, 1])
                left_feat, pos_score = net(left, pos_right)
                pred = pos_score
                pred_list += list(pred.numpy())
            test_result = valid_and_test(pred_list, simnet_process, "test") 
            if args.compute_accuracy: 
                test_auc, test_acc = test_result
                logging.info("AUC of test is %f, Accuracy of test is %f" %
                            (test_auc, test_acc))
            else:
                test_auc = test_result
                logging.info("AUC of test is %f" % test_auc)
        

def test(conf_dict, args):
    """
    Evaluation Function
    """
    logging.info("start test process ...")
    if args.use_cuda:
        place = fluid.CUDAPlace(0)
    else:
        place = fluid.CPUPlace()
    with fluid.dygraph.guard(place):
        vocab = utils.load_vocab(args.vocab_path)
        simnet_process = reader.SimNetProcessor(args, vocab)
        test_pyreader = fluid.io.PyReader(capacity=16, return_list=True, use_double_buffer=False)
        get_test_examples = simnet_process.get_reader("test")
        test_pyreader.decorate_sample_list_generator(
                paddle.batch(get_test_examples, batch_size=args.batch_size),
                place)
     
        conf_dict['dict_size'] = len(vocab)

        net = utils.import_class("./nets",
                                conf_dict["net"]["module_name"],
                                conf_dict["net"]["class_name"])(conf_dict)
       
        model, _ = fluid.dygraph.load_dygraph(args.init_checkpoint)
        net.set_dict(model)
        metric = fluid.metrics.Auc(name="auc")
        pred_list = []
        with io.open("predictions.txt", "w", encoding="utf8") as predictions_file:
            if args.task_mode == "pairwise":
                for left, pos_right in test_pyreader():
                    left = fluid.layers.reshape(left, shape=[-1, 1])
                    pos_right = fluid.layers.reshape(pos_right, shape=[-1, 1])
                
                    left_feat, pos_score = net(left, pos_right)
                    pred = pos_score
                    # pred_list += list(pred.numpy())
                    pred_list += list(map(lambda item: float(item[0]), pred.numpy()[0]))
                    predictions_file.write(u"\n".join(
                            map(lambda item: str((item[0] + 1) / 2), pred.numpy()[0])) + "\n")
            else:
                for left, right in test_pyreader():
                    left = fluid.layers.reshape(left, shape=[-1, 1])
                    right = fluid.layers.reshape(right, shape=[-1, 1])
                    left_feat, pred = net(left, right)
                    # pred_list += list(pred.numpy())
                    pred_list += list(map(lambda item: float(item[0]), pred.numpy()[0]))
                    predictions_file.write(u"\n".join(
                            map(lambda item: str(np.argmax(item)), pred.numpy()[0])) + "\n")

            if args.task_mode == "pairwise":
                pred_list = np.array(pred_list).reshape((-1, 1))
                pred_list = (pred_list + 1) / 2
                pred_list = np.hstack(
                    (np.ones_like(pred_list) - pred_list, pred_list))
            else:
                pred_list = np.array(pred_list)
            labels = simnet_process.get_test_label()

            metric.update(pred_list, labels)
            if args.compute_accuracy:
                acc = utils.get_accuracy(pred_list, labels, args.task_mode,
                                        args.lamda)
                logging.info("AUC of test is %f, Accuracy of test is %f" %
                            (metric.eval(), acc))
            else:
                logging.info("AUC of test is %f" % metric.eval())

        if args.verbose_result:
            utils.get_result_file(args)
            logging.info("test result saved in %s" %
                        os.path.join(os.getcwd(), args.test_result_path))


def infer(conf_dict, args):
    """
    run predict
    """
    logging.info("start test process ...")
    if args.use_cuda:
        place = fluid.CUDAPlace(0)
    else:
        place = fluid.CPUPlace()
   

    vocab = utils.load_vocab(args.vocab_path)
    simnet_process = reader.SimNetProcessor(args, vocab)
    get_infer_examples = simnet_process.get_infer_reader
    infer_pyreader = fluid.io.PyReader(capacity=16, return_list=True, use_double_buffer=False)
    infer_pyreader.decorate_sample_list_generator(
                paddle.batch(get_infer_examples, batch_size=args.batch_size),
                place) 
    
    conf_dict['dict_size'] = len(vocab)

    net = utils.import_class("./nets",
                             conf_dict["net"]["module_name"],
                             conf_dict["net"]["class_name"])(conf_dict)
    model, _ = fluid.dygraph.load_dygraph(args.init_checkpoint)
    net.set_dict(model)
    pred_list = []
    if args.task_mode == "pairwise":
        for left, pos_right in infer_pyreader():
            left = fluid.layers.reshape(left, shape=[-1, 1])
            pos_right = fluid.layers.reshape(pos_right, shape=[-1, 1])
               
            left_feat, pos_score = net(left, pos_right)
            pred = pos_score
            preds_list += list(
                        map(lambda item: str((item[0] + 1) / 2), pred.numpy()[0]))
        
    else:
        for left, right in infer_pyreader():
            left = fluid.layers.reshape(left, shape=[-1, 1])
            pos_right = fluid.layers.reshape(right, shape=[-1, 1])
            left_feat, pred = net(left, right)
            preds_list += map(lambda item: str(np.argmax(item)), pred.numpy()[0])
      
   
    with io.open(args.infer_result_path, "w", encoding="utf8") as infer_file:
        for _data, _pred in zip(simnet_process.get_infer_data(), preds_list):
            infer_file.write(_data + "\t" + _pred + "\n")
    logging.info("infer result saved in %s" %
                 os.path.join(os.getcwd(), args.infer_result_path))


def get_cards():
    num = 0
    cards = os.environ.get('CUDA_VISIBLE_DEVICES', '')
    if cards != '':
        num = len(cards.split(","))
    return num

if __name__ == "__main__":

    args = ArgConfig()
    args = args.build_conf()

    utils.print_arguments(args)
    check_cuda(args.use_cuda)
    check_version()
    utils.init_log("./log/TextSimilarityNet")
    conf_dict = config.SimNetConfig(args)
    if args.do_train:
        train(conf_dict, args)
    elif args.do_test:
        test(conf_dict, args)
    elif args.do_infer:
        infer(conf_dict, args)
    else:
        raise ValueError(
            "one of do_train and do_test and do_infer must be True")