vignesh-trustt
commited on
Commit
•
269bc71
1
Parent(s):
71fe2f3
Upload handler.py
Browse files- handler.py +44 -0
handler.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, Any
|
2 |
+
import logging
|
3 |
+
|
4 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
5 |
+
from peft import PeftConfig, PeftModel
|
6 |
+
import torch.cuda
|
7 |
+
|
8 |
+
|
9 |
+
LOGGER = logging.getLogger(__name__)
|
10 |
+
logging.basicConfig(level=logging.INFO)
|
11 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
12 |
+
|
13 |
+
|
14 |
+
class EndpointHandler():
|
15 |
+
def __init__(self, path=""):
|
16 |
+
config = PeftConfig.from_pretrained(path)
|
17 |
+
model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, load_in_4bit=True, device_map='auto')
|
18 |
+
self.tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
|
19 |
+
# Load the Lora model
|
20 |
+
self.model = PeftModel.from_pretrained(model, path)
|
21 |
+
|
22 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
23 |
+
"""
|
24 |
+
Args:
|
25 |
+
data (Dict): The payload with the text prompt and generation parameters.
|
26 |
+
"""
|
27 |
+
LOGGER.info(f"Received data: {data}")
|
28 |
+
# Get inputs
|
29 |
+
prompt = data.pop("inputs", None)
|
30 |
+
parameters = data.pop("parameters", None)
|
31 |
+
if prompt is None:
|
32 |
+
raise ValueError("Missing prompt.")
|
33 |
+
# Preprocess
|
34 |
+
input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
35 |
+
# Forward
|
36 |
+
LOGGER.info(f"Start generation.")
|
37 |
+
if parameters is not None:
|
38 |
+
output = self.model.generate(input_ids=input_ids, **parameters)
|
39 |
+
else:
|
40 |
+
output = self.model.generate(input_ids=input_ids)
|
41 |
+
# Postprocess
|
42 |
+
prediction = self.tokenizer.decode(output[0])
|
43 |
+
LOGGER.info(f"Generated text: {prediction}")
|
44 |
+
return {"generated_text": prediction}
|