Ozgur98's picture
Update handler.py
153c980
raw
history blame
No virus
1.46 kB
from typing import Dict, Any
import logging
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch.cuda
device = "cuda" if torch.cuda.is_available() else "cpu"
LOGGER = logging.getLogger(__name__)
class EndpointHandler():
def __init__(self, path=""):
self.model = AutoModelForCausalLM.from_pretrained("bigscience/bloom-3b", load_in_8bit=True, device_map='auto')
self.tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom-3b")
# Load the Lora model
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
"""
Args:
data (Dict): The payload with the text prompt and generation parameters.
"""
LOGGER.info(f"Received data: {data}")
# Get inputs
prompt = data.pop("inputs", None)
parameters = data.pop("parameters", None)
if prompt is None:
raise ValueError("Missing prompt.")
# Preprocess
input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(device)
# Forward
LOGGER.info(f"Start generation.")
if parameters is not None:
output = self.model.generate(input_ids=input_ids, **parameters)
else:
output = self.model.generate(input_ids=input_ids)
# Postprocess
prediction = self.tokenizer.decode(output[0])
LOGGER.info(f"Generated text: {prediction}")
return {"generated_text": prediction}