Create handler.py
Browse files- handler.py +57 -0
handler.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Any
|
2 |
+
from unsloth.chat_templates import get_chat_template
|
3 |
+
from unsloth import FastLanguageModel
|
4 |
+
class EndpointHandler():
|
5 |
+
def __init__(self, path=""):
|
6 |
+
# Preload all the elements you are going to need at inference.
|
7 |
+
# pseudo:
|
8 |
+
# self.model= load_model(path)
|
9 |
+
max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
|
10 |
+
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
|
11 |
+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
|
12 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
13 |
+
model_name = path, # YOUR MODEL YOU USED FOR TRAINING
|
14 |
+
max_seq_length = max_seq_length,
|
15 |
+
dtype = dtype,
|
16 |
+
load_in_4bit = load_in_4bit,
|
17 |
+
# token=hftoken
|
18 |
+
)
|
19 |
+
FastLanguageModel.for_inference(model)
|
20 |
+
self.model = model
|
21 |
+
self.tokenizer = tokenizer
|
22 |
+
|
23 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
24 |
+
"""
|
25 |
+
data args:
|
26 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
27 |
+
kwargs
|
28 |
+
Return:
|
29 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
30 |
+
"""
|
31 |
+
|
32 |
+
# pseudo
|
33 |
+
# self.model(input)
|
34 |
+
messages = data
|
35 |
+
# tokenizer = self.tokenizer
|
36 |
+
self.tokenizer = get_chat_template(
|
37 |
+
self.tokenizer,
|
38 |
+
chat_template = "chatml", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
|
39 |
+
mapping = {"role" : "from",
|
40 |
+
"content" : "value",
|
41 |
+
"user" : "human",
|
42 |
+
"assistant" : "gpt"}, # ShareGPT style
|
43 |
+
map_eos_token = True, # Maps <|im_end|> to instead
|
44 |
+
)
|
45 |
+
inputs = self.tokenizer.apply_chat_template(
|
46 |
+
messages,
|
47 |
+
tokenize = True,
|
48 |
+
add_generation_prompt = True, # Must add for generation
|
49 |
+
return_tensors = "pt",
|
50 |
+
).to("cuda")
|
51 |
+
|
52 |
+
# from transformers import TextStreamer
|
53 |
+
# text_streamer = TextStreamer(tokenizer)
|
54 |
+
# _ = model.generate(input_ids = inputs, streamer = text_streamer, max_new_tokens = 128, use_cache = True)
|
55 |
+
outputs = self.model.generate(input_ids = inputs, max_new_tokens = 64, use_cache = True)
|
56 |
+
# print(outputs)
|
57 |
+
return self.tokenizer.batch_decode(outputs)
|