Update handler.py
Browse files- handler.py +35 -68
handler.py
CHANGED
@@ -1,75 +1,42 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
from typing import Dict, Any
|
4 |
import torch
|
|
|
5 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
|
6 |
|
7 |
|
8 |
-
def
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
en_set = set(VOCABS["en"])
|
15 |
-
ar_set = set(VOCABS["ar"])
|
16 |
-
|
17 |
-
# percentage of non-english characters
|
18 |
-
wset = set(txt)
|
19 |
-
inter_en = wset & en_set
|
20 |
-
inter_ar = wset & ar_set
|
21 |
-
if len(inter_en) >= len(inter_ar):
|
22 |
-
return "en"
|
23 |
-
else:
|
24 |
-
return "ar"
|
25 |
|
26 |
-
|
27 |
-
class EndpointHandler:
|
28 |
def __init__(self, path=""):
|
29 |
-
self.
|
30 |
-
self.
|
31 |
-
|
32 |
-
self.
|
33 |
-
|
34 |
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
35 |
-
self.
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
input_ids = self.tokenizer(text, return_tensors="pt").input_ids
|
57 |
-
input_ids = input_ids.to(self.device)
|
58 |
-
input_len = input_ids.shape[-1]
|
59 |
-
generate_ids = self.model.generate(
|
60 |
-
input_ids,
|
61 |
-
top_p=0.9,
|
62 |
-
temperature=0.3,
|
63 |
-
max_new_tokens=2048 - input_len,
|
64 |
-
min_length=input_len + 4,
|
65 |
-
repetition_penalty=1.2,
|
66 |
-
do_sample=True,
|
67 |
-
)
|
68 |
-
response = self.tokenizer.batch_decode(
|
69 |
-
generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
|
70 |
-
)[0]
|
71 |
-
final_response = response.split("### Response: [|AI|]")
|
72 |
-
turn = [f'[|Human|] {query}', f'[|AI|] {final_response[-1]}']
|
73 |
-
chat_history.extend(turn)
|
74 |
-
|
75 |
-
return {"response": final_response, "chat_history": chat_history}
|
|
|
1 |
+
from typing import Dict, List, Any
|
|
|
|
|
2 |
import torch
|
3 |
+
from accelerate import Accelerator
|
4 |
from transformers import AutoTokenizer, AutoModelForCausalLM
|
5 |
+
import numpy as np
|
6 |
|
7 |
|
8 |
+
def softmax(x):
|
9 |
+
z = x - max(x)
|
10 |
+
numerator = np.exp(z)
|
11 |
+
denominator = np.sum(numerator)
|
12 |
+
softmax = numerator/denominator
|
13 |
+
return softmax
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
class EndpointHandler():
|
|
|
16 |
def __init__(self, path=""):
|
17 |
+
self.accelerator = Accelerator()
|
18 |
+
self.device = self.accelerator.device
|
19 |
+
self.model = AutoModelForCausalLM.from_pretrained(path, trust_remote_code=True, device_map="auto")
|
20 |
+
self.model = self.accelerator.prepare(self.model)
|
|
|
21 |
self.tokenizer = AutoTokenizer.from_pretrained(path)
|
22 |
+
self.options_tokens = [self.tokenizer.encode(choice)[-1] for choice in ["A", "B", "C", "D"]]
|
23 |
+
|
24 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
25 |
+
"""
|
26 |
+
data args:
|
27 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
28 |
+
kwargss
|
29 |
+
Return:
|
30 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
31 |
+
"""
|
32 |
+
with torch.no_grad():
|
33 |
+
prompt = data.pop("prompt")
|
34 |
+
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
|
35 |
+
input_size = inputs['input_ids'].size(1)
|
36 |
+
input_ids = inputs["input_ids"].to(self.device)
|
37 |
+
outputs = self.model(**inputs)
|
38 |
+
last_token_logits = outputs.logits[:, -1, :]
|
39 |
+
options_tokens_logits = last_token_logits[:, self.options_tokens].detach().cpu().numpy()
|
40 |
+
conf = softmax(options_tokens_logits[0])
|
41 |
+
pred = np.argmax(options_tokens_logits[0])
|
42 |
+
return [{"pred": pred, "conf":conf}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|