|
| 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 | +import os |
| 16 | +from functools import partial |
| 17 | +import argparse |
| 18 | +from pprint import pprint |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +import paddle |
| 22 | +import paddle.nn as nn |
| 23 | +import paddle.nn.functional as F |
| 24 | +from paddle.nn import TransformerEncoder, TransformerEncoderLayer |
| 25 | + |
| 26 | +from paddlenlp.transformers import ErnieTokenizer, ErnieModel |
| 27 | +from paddlenlp.data import Pad, Tuple |
| 28 | +from paddlenlp.datasets import load_dataset |
| 29 | +from paddlenlp.ops import enable_faster_encoder, disable_faster_encoder |
| 30 | + |
| 31 | +from data import read_text_pair, convert_example, create_dataloader |
| 32 | + |
| 33 | + |
| 34 | +def parse_args(): |
| 35 | + parser = argparse.ArgumentParser() |
| 36 | + parser.add_argument( |
| 37 | + "--text_pair_file", |
| 38 | + type=str, |
| 39 | + required=True, |
| 40 | + help="The full path of input file") |
| 41 | + parser.add_argument( |
| 42 | + "--output_emb_size", |
| 43 | + default=None, |
| 44 | + type=int, |
| 45 | + help="output_embedding_size") |
| 46 | + parser.add_argument( |
| 47 | + "--params_path", |
| 48 | + type=str, |
| 49 | + required=True, |
| 50 | + help="The path to model parameters to be loaded.") |
| 51 | + parser.add_argument( |
| 52 | + "--max_seq_length", |
| 53 | + default=64, |
| 54 | + type=int, |
| 55 | + help="The maximum total input sequence length after tokenization. " |
| 56 | + "Sequences longer than this will be truncated, sequences shorter will be padded." |
| 57 | + ) |
| 58 | + parser.add_argument( |
| 59 | + "--dropout", default=0.0, type=float, help="Dropout probability.") |
| 60 | + parser.add_argument( |
| 61 | + "--batch_size", |
| 62 | + default=32, |
| 63 | + type=int, |
| 64 | + help="Batch size per GPU/CPU for training.") |
| 65 | + parser.add_argument("--seed", default=42, type=int, help="Random seed.") |
| 66 | + parser.add_argument( |
| 67 | + "--pad_to_max_seq_len", |
| 68 | + action="store_true", |
| 69 | + help="Whether to pad to max_seq_len.") |
| 70 | + |
| 71 | + args = parser.parse_args() |
| 72 | + return args |
| 73 | + |
| 74 | + |
| 75 | +class SemanticIndexingPredictor(nn.Layer): |
| 76 | + def __init__(self, |
| 77 | + pretrained_model, |
| 78 | + output_emb_size, |
| 79 | + n_layer=12, |
| 80 | + n_head=12, |
| 81 | + hidden_size=768, |
| 82 | + dim_feedforward=3072, |
| 83 | + activation="relu", |
| 84 | + bos_id=0, |
| 85 | + dropout=0, |
| 86 | + max_seq_len=128, |
| 87 | + is_gelu=False): |
| 88 | + super(SemanticIndexingPredictor, self).__init__() |
| 89 | + size_per_head = hidden_size // n_head |
| 90 | + self.bos_id = bos_id |
| 91 | + self.ptm = pretrained_model |
| 92 | + self.dropout = nn.Dropout(dropout if dropout is not None else 0.0) |
| 93 | + self.output_emb_size = output_emb_size |
| 94 | + if output_emb_size > 0: |
| 95 | + weight_attr = paddle.ParamAttr( |
| 96 | + initializer=paddle.nn.initializer.TruncatedNormal(std=0.02)) |
| 97 | + self.emb_reduce_linear = paddle.nn.Linear( |
| 98 | + 768, output_emb_size, weight_attr=weight_attr) |
| 99 | + encoder_layer = TransformerEncoderLayer( |
| 100 | + hidden_size, n_head, dim_feedforward, dropout=dropout) |
| 101 | + self.ptm.encoder = TransformerEncoder(encoder_layer, n_layer) |
| 102 | + |
| 103 | + def get_pooled_embedding(self, |
| 104 | + input_ids, |
| 105 | + token_type_ids=None, |
| 106 | + position_ids=None, |
| 107 | + attention_mask=None): |
| 108 | + src_mask = (input_ids != self.bos_id |
| 109 | + ).astype(self.ptm.encoder.layers[0].norm1.bias.dtype) |
| 110 | + src_mask = paddle.unsqueeze(src_mask, axis=[1, 2]) |
| 111 | + src_mask.stop_gradient = True |
| 112 | + |
| 113 | + ones = paddle.ones_like(input_ids, dtype="int64") |
| 114 | + seq_length = paddle.cumsum(ones, axis=1) |
| 115 | + position_ids = seq_length - ones |
| 116 | + position_ids.stop_gradient = True |
| 117 | + |
| 118 | + embedding_output = self.ptm.embeddings( |
| 119 | + input_ids=input_ids, |
| 120 | + position_ids=position_ids, |
| 121 | + token_type_ids=token_type_ids) |
| 122 | + sequence_output = self.ptm.encoder(embedding_output, src_mask) |
| 123 | + cls_embedding = self.ptm.pooler(sequence_output) |
| 124 | + |
| 125 | + if self.output_emb_size > 0: |
| 126 | + cls_embedding = self.emb_reduce_linear(cls_embedding) |
| 127 | + cls_embedding = self.dropout(cls_embedding) |
| 128 | + cls_embedding = F.normalize(cls_embedding, p=2, axis=-1) |
| 129 | + |
| 130 | + return cls_embedding |
| 131 | + |
| 132 | + def forward(self, |
| 133 | + query_input_ids, |
| 134 | + title_input_ids, |
| 135 | + query_token_type_ids=None, |
| 136 | + query_position_ids=None, |
| 137 | + query_attention_mask=None, |
| 138 | + title_token_type_ids=None, |
| 139 | + title_position_ids=None, |
| 140 | + title_attention_mask=None): |
| 141 | + query_cls_embedding = self.get_pooled_embedding( |
| 142 | + query_input_ids, query_token_type_ids, query_position_ids, |
| 143 | + query_attention_mask) |
| 144 | + title_cls_embedding = self.get_pooled_embedding( |
| 145 | + title_input_ids, title_token_type_ids, title_position_ids, |
| 146 | + title_attention_mask) |
| 147 | + cosine_sim = paddle.sum(query_cls_embedding * title_cls_embedding, |
| 148 | + axis=-1) |
| 149 | + return cosine_sim |
| 150 | + |
| 151 | + def load(self, init_from_params): |
| 152 | + if init_from_params and os.path.isfile(init_from_params): |
| 153 | + state_dict = paddle.load(init_from_params) |
| 154 | + self.set_state_dict(state_dict) |
| 155 | + print("Loaded parameters from %s" % init_from_params) |
| 156 | + else: |
| 157 | + raise ValueError( |
| 158 | + "Please set --params_path with correct pretrained model file") |
| 159 | + |
| 160 | + |
| 161 | +def do_predict(args): |
| 162 | + place = paddle.set_device("gpu") |
| 163 | + paddle.seed(args.seed) |
| 164 | + tokenizer = ErnieTokenizer.from_pretrained('ernie-1.0') |
| 165 | + |
| 166 | + trans_func = partial( |
| 167 | + convert_example, |
| 168 | + tokenizer=tokenizer, |
| 169 | + max_seq_length=args.max_seq_length, |
| 170 | + pad_to_max_seq_len=args.pad_to_max_seq_len) |
| 171 | + |
| 172 | + batchify_fn = lambda samples, fn=Tuple( |
| 173 | + Pad(axis=0, pad_val=tokenizer.pad_token_id), # query_input |
| 174 | + Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # query_segment |
| 175 | + Pad(axis=0, pad_val=tokenizer.pad_token_id), # title_input |
| 176 | + Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # tilte_segment |
| 177 | + ): [data for data in fn(samples)] |
| 178 | + |
| 179 | + valid_ds = load_dataset( |
| 180 | + read_text_pair, data_path=args.text_pair_file, lazy=False) |
| 181 | + |
| 182 | + valid_data_loader = create_dataloader( |
| 183 | + valid_ds, |
| 184 | + mode="predict", |
| 185 | + batch_size=args.batch_size, |
| 186 | + batchify_fn=batchify_fn, |
| 187 | + trans_fn=trans_func) |
| 188 | + |
| 189 | + pretrained_model = ErnieModel.from_pretrained("ernie-1.0") |
| 190 | + |
| 191 | + model = SemanticIndexingPredictor( |
| 192 | + pretrained_model, |
| 193 | + args.output_emb_size, |
| 194 | + max_seq_len=args.max_seq_length, |
| 195 | + dropout=args.dropout) |
| 196 | + model.eval() |
| 197 | + model.load(args.params_path) |
| 198 | + model = enable_faster_encoder(model) |
| 199 | + cosine_sims = [] |
| 200 | + for batch_data in valid_data_loader: |
| 201 | + query_input_ids, query_token_type_ids, title_input_ids, title_token_type_ids = batch_data |
| 202 | + query_input_ids = paddle.to_tensor(query_input_ids) |
| 203 | + query_token_type_ids = paddle.to_tensor(query_token_type_ids) |
| 204 | + title_input_ids = paddle.to_tensor(title_input_ids) |
| 205 | + title_token_type_ids = paddle.to_tensor(title_token_type_ids) |
| 206 | + batch_cosine_sim = model( |
| 207 | + query_input_ids=query_input_ids, |
| 208 | + title_input_ids=title_input_ids, |
| 209 | + query_token_type_ids=query_token_type_ids, |
| 210 | + title_token_type_ids=title_token_type_ids).numpy() |
| 211 | + cosine_sims.append(batch_cosine_sim) |
| 212 | + |
| 213 | + cosine_sims = np.concatenate(cosine_sims, axis=0) |
| 214 | + for cosine in cosine_sims: |
| 215 | + print('{}'.format(cosine)) |
| 216 | + model = disable_faster_encoder(model) |
| 217 | + |
| 218 | + |
| 219 | +if __name__ == "__main__": |
| 220 | + args = parse_args() |
| 221 | + pprint(args) |
| 222 | + do_predict(args) |
0 commit comments