|
from typing import Any, Dict |
|
|
|
import torch |
|
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig |
|
|
|
|
|
|
|
|
|
class EndpointHandler: |
|
def __init__(self, path=""): |
|
|
|
self.tokenizer = AutoTokenizer.from_pretrained(path) |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
path, |
|
|
|
|
|
device_map="auto", |
|
torch_dtype=torch.float16, |
|
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
self.model = model |
|
self.device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
def __call__(self, data: Dict[str, Any]) -> Dict[str, str]: |
|
|
|
inputs = data.pop("inputs", data) |
|
parameters = data.pop("parameters", None) |
|
|
|
|
|
inputs = self.tokenizer(f"User: {inputs}\n\n", return_tensors="pt") |
|
|
|
|
|
if parameters is not None: |
|
outputs = self.model.generate(**inputs.to(self.device), max_new_tokens=880, **parameters) |
|
else: |
|
outputs = self.model.generate(**inputs.to(self.device), max_new_tokens=880) |
|
|
|
|
|
prediction = self.tokenizer.decode(outputs[0], skip_special_tokens=True) |
|
|
|
return [{"generated_text": prediction}] |