|
| 1 | +# Copyright (c) 2023 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 distutils.util |
| 16 | +import os |
| 17 | + |
| 18 | +import fastdeploy as fd |
| 19 | +import numpy as np |
| 20 | + |
| 21 | +from paddlenlp.transformers import AutoTokenizer |
| 22 | + |
| 23 | + |
| 24 | +def parse_arguments(): |
| 25 | + import argparse |
| 26 | + |
| 27 | + parser = argparse.ArgumentParser() |
| 28 | + parser.add_argument("--model_dir", required=True, help="The directory of model.") |
| 29 | + parser.add_argument("--vocab_path", type=str, default="", help="The path of tokenizer vocab.") |
| 30 | + parser.add_argument("--model_prefix", type=str, default="model", help="The model and params file prefix.") |
| 31 | + parser.add_argument( |
| 32 | + "--device", |
| 33 | + type=str, |
| 34 | + default="cpu", |
| 35 | + choices=["gpu", "cpu"], |
| 36 | + help="Type of inference device, support 'cpu' or 'gpu'.", |
| 37 | + ) |
| 38 | + parser.add_argument( |
| 39 | + "--backend", |
| 40 | + type=str, |
| 41 | + default="paddle", |
| 42 | + choices=["onnx_runtime", "paddle", "openvino", "tensorrt", "paddle_tensorrt"], |
| 43 | + help="The inference runtime backend.", |
| 44 | + ) |
| 45 | + parser.add_argument("--cpu_threads", type=int, default=1, help="Number of threads to predict when using cpu.") |
| 46 | + parser.add_argument("--device_id", type=int, default=0, help="Select which gpu device to train model.") |
| 47 | + parser.add_argument("--batch_size", type=int, default=1, help="The batch size of data.") |
| 48 | + parser.add_argument("--max_length", type=int, default=128, help="The max length of sequence.") |
| 49 | + parser.add_argument("--log_interval", type=int, default=10, help="The interval of logging.") |
| 50 | + parser.add_argument("--use_fp16", type=distutils.util.strtobool, default=False, help="Wheter to use FP16 mode") |
| 51 | + parser.add_argument( |
| 52 | + "--use_fast", |
| 53 | + type=distutils.util.strtobool, |
| 54 | + default=True, |
| 55 | + help="Whether to use fast_tokenizer to accelarate the tokenization.", |
| 56 | + ) |
| 57 | + return parser.parse_args() |
| 58 | + |
| 59 | + |
| 60 | +def batchfy_text(texts, batch_size): |
| 61 | + batch_texts = [] |
| 62 | + batch_start = 0 |
| 63 | + while batch_start < len(texts): |
| 64 | + batch_texts += [texts[batch_start : min(batch_start + batch_size, len(texts))]] |
| 65 | + batch_start += batch_size |
| 66 | + return batch_texts |
| 67 | + |
| 68 | + |
| 69 | +class Predictor(object): |
| 70 | + def __init__(self, args): |
| 71 | + self.tokenizer = AutoTokenizer.from_pretrained(args.model_dir, use_fast=args.use_fast) |
| 72 | + self.runtime = self.create_fd_runtime(args) |
| 73 | + self.batch_size = args.batch_size |
| 74 | + self.max_length = args.max_length |
| 75 | + |
| 76 | + def create_fd_runtime(self, args): |
| 77 | + option = fd.RuntimeOption() |
| 78 | + model_path = os.path.join(args.model_dir, args.model_prefix + ".pdmodel") |
| 79 | + params_path = os.path.join(args.model_dir, args.model_prefix + ".pdiparams") |
| 80 | + option.set_model_path(model_path, params_path) |
| 81 | + if args.device == "cpu": |
| 82 | + option.use_cpu() |
| 83 | + option.set_cpu_thread_num(args.cpu_threads) |
| 84 | + else: |
| 85 | + option.use_gpu(args.device_id) |
| 86 | + if args.backend == "paddle": |
| 87 | + option.use_paddle_infer_backend() |
| 88 | + elif args.backend == "onnx_runtime": |
| 89 | + option.use_ort_backend() |
| 90 | + elif args.backend == "openvino": |
| 91 | + option.use_openvino_backend() |
| 92 | + else: |
| 93 | + option.use_trt_backend() |
| 94 | + if args.backend == "paddle_tensorrt": |
| 95 | + option.use_paddle_infer_backend() |
| 96 | + option.paddle_infer_option.collect_trt_shape = True |
| 97 | + option.paddle_infer_option.enable_trt = True |
| 98 | + trt_file = os.path.join(args.model_dir, "model.trt") |
| 99 | + option.trt_option.set_shape( |
| 100 | + "input_ids", [1, 1], [args.batch_size, args.max_length], [args.batch_size, args.max_length] |
| 101 | + ) |
| 102 | + option.trt_option.set_shape( |
| 103 | + "token_type_ids", [1, 1], [args.batch_size, args.max_length], [args.batch_size, args.max_length] |
| 104 | + ) |
| 105 | + if args.use_fp16: |
| 106 | + option.trt_option.enable_fp16 = True |
| 107 | + trt_file = trt_file + ".fp16" |
| 108 | + option.trt_option.serialize_file = trt_file |
| 109 | + return fd.Runtime(option) |
| 110 | + |
| 111 | + def preprocess(self, text): |
| 112 | + data = self.tokenizer(text, max_length=self.max_length, padding=True, truncation=True) |
| 113 | + input_ids_name = self.runtime.get_input_info(0).name |
| 114 | + token_type_ids_name = self.runtime.get_input_info(1).name |
| 115 | + input_map = { |
| 116 | + input_ids_name: np.array(data["input_ids"], dtype="int64"), |
| 117 | + token_type_ids_name: np.array(data["token_type_ids"], dtype="int64"), |
| 118 | + } |
| 119 | + return input_map |
| 120 | + |
| 121 | + def infer(self, input_map): |
| 122 | + results = self.runtime.infer(input_map) |
| 123 | + return results |
| 124 | + |
| 125 | + def postprocess(self, infer_data): |
| 126 | + logits = np.array(infer_data[0]) |
| 127 | + max_value = np.max(logits, axis=1, keepdims=True) |
| 128 | + exp_data = np.exp(logits - max_value) |
| 129 | + probs = exp_data / np.sum(exp_data, axis=1, keepdims=True) |
| 130 | + out_dict = {"label": probs.argmax(axis=-1), "confidence": probs} |
| 131 | + return out_dict |
| 132 | + |
| 133 | + def predict(self, texts): |
| 134 | + input_map = self.preprocess(texts) |
| 135 | + infer_result = self.infer(input_map) |
| 136 | + output = self.postprocess(infer_result) |
| 137 | + return output |
| 138 | + |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + args = parse_arguments() |
| 142 | + predictor = Predictor(args) |
| 143 | + texts_ds = [ |
| 144 | + "against shimmering cinematography that lends the setting the ethereal beauty of an asian landscape painting", |
| 145 | + "the situation in a well-balanced fashion", |
| 146 | + "at achieving the modest , crowd-pleasing goals it sets for itself", |
| 147 | + "so pat it makes your teeth hurt", |
| 148 | + "this new jangle of noise , mayhem and stupidity must be a serious contender for the title .", |
| 149 | + ] |
| 150 | + label_map = {0: "negative", 1: "positive"} |
| 151 | + batch_texts = batchfy_text(texts_ds, args.batch_size) |
| 152 | + for bs, texts in enumerate(batch_texts): |
| 153 | + outputs = predictor.predict(texts) |
| 154 | + for i, sentence1 in enumerate(texts): |
| 155 | + print( |
| 156 | + f"Batch id: {bs}, example id: {i}, sentence1: {sentence1}, " |
| 157 | + f"label: {label_map[outputs['label'][i]]}, negative prob: {outputs['confidence'][i][0]:.4f}, " |
| 158 | + f"positive prob: {outputs['confidence'][i][1]:.4f}." |
| 159 | + ) |
0 commit comments