|
| 1 | +import logging |
| 2 | +from abc import ABC |
| 3 | + |
| 4 | +import torch |
| 5 | +import transformers |
| 6 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 7 | + |
| 8 | +from ts.context import Context |
| 9 | +from ts.torch_handler.base_handler import BaseHandler |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | +logger.info("Transformers version %s", transformers.__version__) |
| 13 | + |
| 14 | + |
| 15 | +class LlamaHandler(BaseHandler, ABC): |
| 16 | + """ |
| 17 | + Transformers handler class for sequence, token classification and question answering. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self): |
| 21 | + super(LlamaHandler, self).__init__() |
| 22 | + self.max_length = None |
| 23 | + self.max_new_tokens = None |
| 24 | + self.tokenizer = None |
| 25 | + self.initialized = False |
| 26 | + |
| 27 | + def initialize(self, ctx: Context): |
| 28 | + """In this initialize function, the HF large model is loaded and |
| 29 | + partitioned using DeepSpeed. |
| 30 | + Args: |
| 31 | + ctx (context): It is a JSON Object containing information |
| 32 | + pertaining to the model artifacts parameters. |
| 33 | + """ |
| 34 | + model_dir = ctx.system_properties.get("model_dir") |
| 35 | + self.max_length = int(ctx.model_yaml_config["handler"]["max_length"]) |
| 36 | + self.max_new_tokens = int(ctx.model_yaml_config["handler"]["max_new_tokens"]) |
| 37 | + model_name = ctx.model_yaml_config["handler"]["model_name"] |
| 38 | + model_path = f'{model_dir}/{ctx.model_yaml_config["handler"]["model_path"]}' |
| 39 | + seed = int(ctx.model_yaml_config["handler"]["manual_seed"]) |
| 40 | + torch.manual_seed(seed) |
| 41 | + |
| 42 | + logger.info("Model %s loading tokenizer", ctx.model_name) |
| 43 | + self.model = AutoModelForCausalLM.from_pretrained( |
| 44 | + model_path, |
| 45 | + device_map="balanced", |
| 46 | + low_cpu_mem_usage=True, |
| 47 | + torch_dtype=torch.float16, |
| 48 | + load_in_8bit=True, |
| 49 | + trust_remote_code=True, |
| 50 | + ) |
| 51 | + if ctx.model_yaml_config["handler"]["fast_kernels"]: |
| 52 | + from optimum.bettertransformer import BetterTransformer |
| 53 | + |
| 54 | + try: |
| 55 | + self.model = BetterTransformer.transform(self.model) |
| 56 | + except RuntimeError as error: |
| 57 | + logger.warning( |
| 58 | + "HuggingFace Optimum is not supporting this model,for the list of supported models, please refer to this doc,https://huggingface.co/docs/optimum/bettertransformer/overview" |
| 59 | + ) |
| 60 | + self.tokenizer = AutoTokenizer.from_pretrained(model_path) |
| 61 | + |
| 62 | + logger.info("Model %s loaded successfully", ctx.model_name) |
| 63 | + self.initialized = True |
| 64 | + |
| 65 | + def preprocess(self, requests): |
| 66 | + """ |
| 67 | + Basic text preprocessing, based on the user's choice of application mode. |
| 68 | + Args: |
| 69 | + requests (list): A list of dictionaries with a "data" or "body" field, each |
| 70 | + containing the input text to be processed. |
| 71 | + Returns: |
| 72 | + tuple: A tuple with two tensors: the batch of input ids and the batch of |
| 73 | + attention masks. |
| 74 | + """ |
| 75 | + input_texts = [data.get("data") or data.get("body") for data in requests] |
| 76 | + input_ids_batch, attention_mask_batch = [], [] |
| 77 | + for input_text in input_texts: |
| 78 | + input_ids, attention_mask = self.encode_input_text(input_text) |
| 79 | + input_ids_batch.append(input_ids) |
| 80 | + attention_mask_batch.append(attention_mask) |
| 81 | + input_ids_batch = torch.cat(input_ids_batch, dim=0).to(self.model.device) |
| 82 | + attention_mask_batch = torch.cat(attention_mask_batch, dim=0).to(self.device) |
| 83 | + return input_ids_batch, attention_mask_batch |
| 84 | + |
| 85 | + def encode_input_text(self, input_text): |
| 86 | + """ |
| 87 | + Encodes a single input text using the tokenizer. |
| 88 | + Args: |
| 89 | + input_text (str): The input text to be encoded. |
| 90 | + Returns: |
| 91 | + tuple: A tuple with two tensors: the encoded input ids and the attention mask. |
| 92 | + """ |
| 93 | + if isinstance(input_text, (bytes, bytearray)): |
| 94 | + input_text = input_text.decode("utf-8") |
| 95 | + logger.info("Received text: '%s'", input_text) |
| 96 | + inputs = self.tokenizer.encode_plus( |
| 97 | + input_text, |
| 98 | + max_length=self.max_length, |
| 99 | + padding=False, |
| 100 | + add_special_tokens=True, |
| 101 | + return_tensors="pt", |
| 102 | + truncation=True, |
| 103 | + ) |
| 104 | + input_ids = inputs["input_ids"] |
| 105 | + attention_mask = inputs["attention_mask"] |
| 106 | + return input_ids, attention_mask |
| 107 | + |
| 108 | + def inference(self, input_batch): |
| 109 | + """ |
| 110 | + Predicts the class (or classes) of the received text using the serialized transformers |
| 111 | + checkpoint. |
| 112 | + Args: |
| 113 | + input_batch (tuple): A tuple with two tensors: the batch of input ids and the batch |
| 114 | + of attention masks, as returned by the preprocess function. |
| 115 | + Returns: |
| 116 | + list: A list of strings with the predicted values for each input text in the batch. |
| 117 | + """ |
| 118 | + input_ids_batch, attention_mask_batch = input_batch |
| 119 | + input_ids_batch = input_ids_batch.to(self.device) |
| 120 | + outputs = self.model.generate( |
| 121 | + input_ids_batch, |
| 122 | + attention_mask=attention_mask_batch, |
| 123 | + max_length=self.max_new_tokens, |
| 124 | + ) |
| 125 | + |
| 126 | + inferences = self.tokenizer.batch_decode( |
| 127 | + outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False |
| 128 | + ) |
| 129 | + |
| 130 | + logger.info("Generated text: %s", inferences) |
| 131 | + return inferences |
| 132 | + |
| 133 | + def postprocess(self, inference_output): |
| 134 | + """Post Process Function converts the predicted response into Torchserve readable format. |
| 135 | + Args: |
| 136 | + inference_output (list): It contains the predicted response of the input text. |
| 137 | + Returns: |
| 138 | + (list): Returns a list of the Predictions and Explanations. |
| 139 | + """ |
| 140 | + return inference_output |
0 commit comments