Create handler.py
Browse files- handler.py +41 -0
handler.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
|
| 4 |
+
class EndpointHandler:
|
| 5 |
+
def __init__(self, model_dir):
|
| 6 |
+
# Load tokenizer and model from the provided model directory
|
| 7 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
| 8 |
+
|
| 9 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 10 |
+
torch_dtype = torch.float16 if self.device == "cuda" else torch.float32
|
| 11 |
+
|
| 12 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 13 |
+
model_dir,
|
| 14 |
+
trust_remote_code=True,
|
| 15 |
+
torch_dtype=torch_dtype,
|
| 16 |
+
device_map="auto" if self.device == "cuda" else None
|
| 17 |
+
)
|
| 18 |
+
self.model.eval()
|
| 19 |
+
|
| 20 |
+
def __call__(self, data):
|
| 21 |
+
# Extract inputs and parameters from the request payload
|
| 22 |
+
inputs = data.get("inputs", "")
|
| 23 |
+
params = data.get("parameters", {})
|
| 24 |
+
|
| 25 |
+
# Tokenize input
|
| 26 |
+
input_ids = self.tokenizer.encode(inputs, return_tensors="pt").to(self.model.device)
|
| 27 |
+
|
| 28 |
+
# Generate response
|
| 29 |
+
with torch.no_grad():
|
| 30 |
+
outputs = self.model.generate(
|
| 31 |
+
input_ids,
|
| 32 |
+
max_new_tokens=params.get("max_new_tokens", 256),
|
| 33 |
+
temperature=params.get("temperature", 0.7),
|
| 34 |
+
top_p=params.get("top_p", 0.95),
|
| 35 |
+
top_k=params.get("top_k", 50),
|
| 36 |
+
do_sample=params.get("do_sample", True)
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# Decode and return
|
| 40 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 41 |
+
return {"generated_text": response}
|