Update handler.py
Browse files- handler.py +37 -35
handler.py
CHANGED
|
@@ -1,35 +1,37 @@
|
|
| 1 |
-
from typing import Dict, List, Any
|
| 2 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 3 |
-
|
| 4 |
-
# Need to set HF_TOKEN on the endpoint creation process for this to work
|
| 5 |
-
model_name = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
| 6 |
-
|
| 7 |
-
class EndpointHandler:
|
| 8 |
-
def __init__(self, path=""):
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
predictions = self.pipeline(inputs)
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, List, Any
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 3 |
+
|
| 4 |
+
# Need to set HF_TOKEN on the endpoint creation process for this to work
|
| 5 |
+
model_name = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
| 6 |
+
|
| 7 |
+
class EndpointHandler:
|
| 8 |
+
def __init__(self, path=""):
|
| 9 |
+
# create inference pipeline
|
| 10 |
+
self.pipeline = pipeline(
|
| 11 |
+
"text-generation",
|
| 12 |
+
model=model_name,
|
| 13 |
+
model_kwargs={"torch_dtype": torch.bfloat16},
|
| 14 |
+
device_map="auto",
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
| 18 |
+
"""
|
| 19 |
+
input args:
|
| 20 |
+
data: a dict with elements...
|
| 21 |
+
inputs: List[List[Dict[str, str]]] or List[str] , inputs to batch-process in conversational format
|
| 22 |
+
parameters: Any , parameters to be passed into model
|
| 23 |
+
outputs:
|
| 24 |
+
list of {'generated_text': str} type outputs
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
inputs = data.pop("inputs", data)
|
| 28 |
+
parameters = data.pop("parameters", None)
|
| 29 |
+
|
| 30 |
+
# pass inputs with all kwargs in data
|
| 31 |
+
if parameters is not None:
|
| 32 |
+
predictions = self.pipeline(inputs, **parameters)
|
| 33 |
+
else:
|
| 34 |
+
predictions = self.pipeline(inputs)
|
| 35 |
+
|
| 36 |
+
# postprocess the prediction
|
| 37 |
+
return [{'next_chat_turn': e[0]["generated_text"][-1]} for e in predictions]
|