|
| 1 | +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from functools import partial |
| 16 | +import argparse |
| 17 | +import sys |
| 18 | +import os |
| 19 | +import random |
| 20 | +import time |
| 21 | + |
| 22 | +import numpy as np |
| 23 | +import paddle |
| 24 | +import paddle.nn.functional as F |
| 25 | +import paddlenlp as ppnlp |
| 26 | +from paddlenlp.datasets import load_dataset |
| 27 | +from paddlenlp.data import Stack, Tuple, Pad |
| 28 | + |
| 29 | +from data import create_dataloader, read_text_pair |
| 30 | +from data import convert_example |
| 31 | + |
| 32 | +# yapf: disable |
| 33 | +parser = argparse.ArgumentParser() |
| 34 | +parser.add_argument("--input_file", type=str, required=True, help="The full path of input file") |
| 35 | +# parser.add_argument("--params_path", type=str, required=True, help="The path to model parameters to be loaded.") |
| 36 | +parser.add_argument("--max_seq_length", default=64, type=int, help="The maximum total input sequence length after tokenization. " |
| 37 | + "Sequences longer than this will be truncated, sequences shorter will be padded.") |
| 38 | +parser.add_argument("--batch_size", default=32, type=int, help="Batch size per GPU/CPU for training.") |
| 39 | +parser.add_argument('--device', choices=['cpu', 'gpu'], default="gpu", help="Select which device to train model, defaults to gpu.") |
| 40 | +args = parser.parse_args() |
| 41 | +# yapf: enable |
| 42 | + |
| 43 | + |
| 44 | +def predict(model, data_loader): |
| 45 | + """ |
| 46 | + Predicts the similarity. |
| 47 | +
|
| 48 | + Args: |
| 49 | + model (obj:`SemanticIndexBase`): A model to extract text embedding or calculate similarity of text pair. |
| 50 | + data_loaer (obj:`List(Example)`): The processed data ids of text pair: [query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids] |
| 51 | + Returns: |
| 52 | + results(obj:`List`): cosine similarity of text pairs. |
| 53 | + """ |
| 54 | + results = [] |
| 55 | + |
| 56 | + model.eval() |
| 57 | + |
| 58 | + with paddle.no_grad(): |
| 59 | + for batch_data in data_loader: |
| 60 | + query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids = batch_data |
| 61 | + query_input_ids = paddle.to_tensor(query_input_ids) |
| 62 | + query_token_type_ids = paddle.to_tensor(query_token_type_ids) |
| 63 | + title_input_ids = paddle.to_tensor(title_input_ids) |
| 64 | + title_token_type_ids = paddle.to_tensor(title_token_type_ids) |
| 65 | + |
| 66 | + vecs_query = model( |
| 67 | + input_ids=query_input_ids, token_type_ids=query_token_type_ids) |
| 68 | + vecs_title = model( |
| 69 | + input_ids=title_input_ids, token_type_ids=title_token_type_ids) |
| 70 | + vecs_query = vecs_query[1].numpy() |
| 71 | + vecs_title = vecs_title[1].numpy() |
| 72 | + |
| 73 | + vecs_query = vecs_query / (vecs_query**2).sum(axis=1, |
| 74 | + keepdims=True)**0.5 |
| 75 | + vecs_title = vecs_title / (vecs_title**2).sum(axis=1, |
| 76 | + keepdims=True)**0.5 |
| 77 | + sims = (vecs_query * vecs_title).sum(axis=1) |
| 78 | + |
| 79 | + results.extend(sims) |
| 80 | + |
| 81 | + return results |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + paddle.set_device(args.device) |
| 86 | + |
| 87 | + model = ppnlp.transformers.BertModel.from_pretrained( |
| 88 | + 'simbert-base-chinese', with_pool='linear') |
| 89 | + tokenizer = ppnlp.transformers.BertTokenizer.from_pretrained( |
| 90 | + 'simbert-base-chinese') |
| 91 | + |
| 92 | + trans_func = partial( |
| 93 | + convert_example, |
| 94 | + tokenizer=tokenizer, |
| 95 | + max_seq_length=args.max_seq_length, |
| 96 | + phase="predict") |
| 97 | + |
| 98 | + batchify_fn = lambda samples, fn=Tuple( |
| 99 | + Pad(axis=0, pad_val=tokenizer.pad_token_id), # query_input |
| 100 | + Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # query_segment |
| 101 | + Pad(axis=0, pad_val=tokenizer.pad_token_id), # title_input |
| 102 | + Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # tilte_segment |
| 103 | + ): [data for data in fn(samples)] |
| 104 | + |
| 105 | + valid_ds = load_dataset( |
| 106 | + read_text_pair, data_path=args.input_file, lazy=False) |
| 107 | + |
| 108 | + valid_data_loader = create_dataloader( |
| 109 | + valid_ds, |
| 110 | + mode='predict', |
| 111 | + batch_size=args.batch_size, |
| 112 | + batchify_fn=batchify_fn, |
| 113 | + trans_fn=trans_func) |
| 114 | + |
| 115 | + y_sims = predict(model, valid_data_loader) |
| 116 | + |
| 117 | + valid_ds = load_dataset( |
| 118 | + read_text_pair, data_path=args.input_file, lazy=False) |
| 119 | + |
| 120 | + for idx, prob in enumerate(y_sims): |
| 121 | + text_pair = valid_ds[idx] |
| 122 | + text_pair["similarity"] = y_sims[idx] |
| 123 | + print(text_pair) |
0 commit comments