shredder-31
commited on
Commit
•
c049366
1
Parent(s):
edcee34
Create handler.py
Browse files- handler.py +34 -0
handler.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
|
3 |
+
class EndpointHandler():
|
4 |
+
def __init__(self , path=""):
|
5 |
+
# Preload all the elements you are going to need at inference.
|
6 |
+
# pseudo:
|
7 |
+
# self.model= load_model(path)
|
8 |
+
bnb_config = BitsAndBytesConfig(
|
9 |
+
load_in_4bit=True,
|
10 |
+
bnb_4bit_use_double_quant=True,
|
11 |
+
bnb_4bit_quant_type="nf4",
|
12 |
+
bnb_4bit_compute_dtype=torch.bfloat16
|
13 |
+
)
|
14 |
+
model = AutoModelForCausalLM.from_pretrained(path, quantization_config=bnb_config, device_map={"":0})
|
15 |
+
tokenizer = AutoTokenizer.from_pretrained(path, add_eos_token=True)
|
16 |
+
self.model = model
|
17 |
+
self.tokenizer = tokenizer
|
18 |
+
|
19 |
+
|
20 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
21 |
+
"""
|
22 |
+
data args:
|
23 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
24 |
+
kwargs
|
25 |
+
Return:
|
26 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
27 |
+
"""
|
28 |
+
|
29 |
+
|
30 |
+
encodeds = self.tokenizer(data['inputs'], return_tensors="pt", add_special_tokens=True)
|
31 |
+
generated_ids = self.model.generate(**encodeds, max_new_tokens=data['max_new_tokens'], do_sample=False)
|
32 |
+
decoded = self.tokenizer.decode(generated_ids[0], skip_special_tokens=True)
|
33 |
+
|
34 |
+
return {'output':decoded[len(data['inputs']):]}
|