|
| 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 six |
| 16 | +import os |
| 17 | +import numpy as np |
| 18 | +import paddle |
| 19 | +import onnxruntime as ort |
| 20 | +from paddlenlp.transformers import AutoTokenizer |
| 21 | + |
| 22 | + |
| 23 | +class InferBackend(object): |
| 24 | + def __init__(self, model_path): |
| 25 | + print(">>> [InferBackend] Creating Engine ...") |
| 26 | + providers = ['CUDAExecutionProvider'] |
| 27 | + sess_options = ort.SessionOptions() |
| 28 | + self.predictor = ort.InferenceSession( |
| 29 | + model_path, sess_options=sess_options, providers=providers) |
| 30 | + if "CUDAExecutionProvider" in self.predictor.get_providers(): |
| 31 | + print(">>> [InferBackend] Use GPU to inference ...") |
| 32 | + else: |
| 33 | + print(">>> [InferBackend] Use CPU to inference ...") |
| 34 | + input_name1 = self.predictor.get_inputs()[1].name |
| 35 | + input_name2 = self.predictor.get_inputs()[0].name |
| 36 | + self.input_handles = [input_name1, input_name2] |
| 37 | + print(">>> [InferBackend] Engine Created ...") |
| 38 | + |
| 39 | + def infer(self, input_dict: dict): |
| 40 | + result = self.predictor.run(None, input_dict) |
| 41 | + return result |
| 42 | + |
| 43 | + |
| 44 | +def token_cls_print_ret(infer_result, input_datas): |
| 45 | + rets = infer_result["value"] |
| 46 | + for i, ret in enumerate(rets): |
| 47 | + print("input data:", input_datas[i]) |
| 48 | + print("The model detects all entities:") |
| 49 | + for iterm in ret: |
| 50 | + print("entity:", iterm["entity"], " label:", iterm["label"], |
| 51 | + " pos:", iterm["pos"]) |
| 52 | + print("-----------------------------") |
| 53 | + |
| 54 | + |
| 55 | +def seq_cls_print_ret(infer_result, input_datas): |
| 56 | + label_list = [ |
| 57 | + "news_story", "news_culture", "news_entertainment", "news_sports", |
| 58 | + "news_finance", "news_house", "news_car", "news_edu", "news_tech", |
| 59 | + "news_military", "news_travel", "news_world", "news_stock", |
| 60 | + "news_agriculture", "news_game" |
| 61 | + ] |
| 62 | + label = infer_result["label"].squeeze().tolist() |
| 63 | + confidence = infer_result["confidence"].squeeze().tolist() |
| 64 | + for i, ret in enumerate(infer_result): |
| 65 | + print("input data:", input_datas[i]) |
| 66 | + print("seq cls result:") |
| 67 | + print("label:", label_list[label[i]], " confidence:", confidence[i]) |
| 68 | + print("-----------------------------") |
| 69 | + |
| 70 | + |
| 71 | +class ErniePredictor(object): |
| 72 | + def __init__(self, args): |
| 73 | + self.task_name = args.task_name |
| 74 | + self.tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) |
| 75 | + if args.task_name == 'seq_cls': |
| 76 | + self.label_names = [] |
| 77 | + self.preprocess = self.seq_cls_preprocess |
| 78 | + self.postprocess = self.seq_cls_postprocess |
| 79 | + self.printer = seq_cls_print_ret |
| 80 | + elif args.task_name == 'token_cls': |
| 81 | + self.label_names = [ |
| 82 | + 'O', 'B-PER', 'I-PER', 'B-ORG', 'I-ORG', 'B-LOC', 'I-LOC' |
| 83 | + ] |
| 84 | + self.preprocess = self.token_cls_preprocess |
| 85 | + self.postprocess = self.token_cls_postprocess |
| 86 | + self.printer = token_cls_print_ret |
| 87 | + else: |
| 88 | + print( |
| 89 | + "[ErniePredictor]: task_name only support seq_cls and token_cls now." |
| 90 | + ) |
| 91 | + exit(0) |
| 92 | + |
| 93 | + self.max_seq_length = args.max_seq_length |
| 94 | + self.inference_backend = InferBackend(args.model_path) |
| 95 | + |
| 96 | + def seq_cls_preprocess(self, input_data: list): |
| 97 | + data = input_data |
| 98 | + # tokenizer + pad |
| 99 | + data = self.tokenizer( |
| 100 | + data, max_length=self.max_seq_length, padding=True, truncation=True) |
| 101 | + input_ids = data["input_ids"] |
| 102 | + token_type_ids = data["token_type_ids"] |
| 103 | + return { |
| 104 | + "input_ids": np.array( |
| 105 | + input_ids, dtype="int64"), |
| 106 | + "token_type_ids": np.array( |
| 107 | + token_type_ids, dtype="int64") |
| 108 | + } |
| 109 | + |
| 110 | + def seq_cls_postprocess(self, infer_data, input_data): |
| 111 | + logits = np.array(infer_data[0]) |
| 112 | + max_value = np.max(logits, axis=1, keepdims=True) |
| 113 | + exp_data = np.exp(logits - max_value) |
| 114 | + probs = exp_data / np.sum(exp_data, axis=1, keepdims=True) |
| 115 | + out_dict = { |
| 116 | + "label": probs.argmax(axis=-1), |
| 117 | + "confidence": probs.max(axis=-1) |
| 118 | + } |
| 119 | + return out_dict |
| 120 | + |
| 121 | + def token_cls_preprocess(self, data: list): |
| 122 | + # tokenizer + pad |
| 123 | + is_split_into_words = False |
| 124 | + if isinstance(data[0], list): |
| 125 | + is_split_into_words = True |
| 126 | + data = self.tokenizer( |
| 127 | + data, |
| 128 | + max_length=self.max_seq_length, |
| 129 | + padding=True, |
| 130 | + truncation=True, |
| 131 | + is_split_into_words=is_split_into_words) |
| 132 | + |
| 133 | + input_ids = data["input_ids"] |
| 134 | + token_type_ids = data["token_type_ids"] |
| 135 | + return { |
| 136 | + "input_ids": np.array( |
| 137 | + input_ids, dtype="int64"), |
| 138 | + "token_type_ids": np.array( |
| 139 | + token_type_ids, dtype="int64") |
| 140 | + } |
| 141 | + |
| 142 | + def token_cls_postprocess(self, infer_data, input_data): |
| 143 | + result = np.array(infer_data[0]) |
| 144 | + tokens_label = result.argmax(axis=-1).tolist() |
| 145 | + # 获取batch中每个token的实体 |
| 146 | + value = [] |
| 147 | + for batch, token_label in enumerate(tokens_label): |
| 148 | + start = -1 |
| 149 | + label_name = "" |
| 150 | + items = [] |
| 151 | + for i, label in enumerate(token_label): |
| 152 | + if self.label_names[label] == "O" and start >= 0: |
| 153 | + entity = input_data[batch][start:i - 1] |
| 154 | + if isinstance(entity, list): |
| 155 | + entity = "".join(entity) |
| 156 | + items.append({ |
| 157 | + "pos": [start, i - 2], |
| 158 | + "entity": entity, |
| 159 | + "label": label_name, |
| 160 | + }) |
| 161 | + start = -1 |
| 162 | + elif "B-" in self.label_names[label]: |
| 163 | + start = i - 1 |
| 164 | + label_name = self.label_names[label][2:] |
| 165 | + if start >= 0: |
| 166 | + items.append({ |
| 167 | + "pos": [start, len(token_label) - 1], |
| 168 | + "entity": input_data[batch][start:len(token_label) - 1], |
| 169 | + "label": "" |
| 170 | + }) |
| 171 | + value.append(items) |
| 172 | + |
| 173 | + out_dict = {"value": value, "tokens_label": tokens_label} |
| 174 | + return out_dict |
| 175 | + |
| 176 | + def infer(self, data): |
| 177 | + return self.inference_backend.infer(data) |
| 178 | + |
| 179 | + def predict(self, input_data: list): |
| 180 | + preprocess_result = self.preprocess(input_data) |
| 181 | + infer_result = self.infer(preprocess_result) |
| 182 | + result = self.postprocess(infer_result, input_data) |
| 183 | + self.printer(result, input_data) |
| 184 | + return result |
0 commit comments