jscore2023
commited on
Commit
•
cac4296
1
Parent(s):
aa68d66
Update handler.py
Browse files- handler.py +29 -22
handler.py
CHANGED
@@ -1,7 +1,13 @@
|
|
|
|
|
|
|
|
1 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
from peft import PeftConfig, PeftModel
|
3 |
-
|
4 |
import torch.cuda
|
|
|
|
|
|
|
|
|
5 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
6 |
|
7 |
|
@@ -13,25 +19,26 @@ class EndpointHandler():
|
|
13 |
# Load the Lora model
|
14 |
self.model = PeftModel.from_pretrained(model, path)
|
15 |
|
16 |
-
|
17 |
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
|
|
|
|
|
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 |
|
|
|
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}
|