Create handler.py
Browse files- handler.py +64 -0
handler.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
%%writefile pipeline.py
|
2 |
+
from typing import Dict, List, Any
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
|
4 |
+
import torch
|
5 |
+
import json
|
6 |
+
|
7 |
+
|
8 |
+
def generate_rag_prompt_message(context, question):
|
9 |
+
prompt = f'Olet tekoälyavustaja joka vastaa annetun kontekstin perusteella asiantuntevasti ja ystävällisesti käyttäjän kysymyksiin\n\nKonteksti: {context}\n\nKysymys: {question}\n\nVastaa yllä olevaan kysymykseen annetun kontekstin perusteella.'
|
10 |
+
prompt = [{'role': 'user', 'content': prompt}]
|
11 |
+
return prompt
|
12 |
+
|
13 |
+
|
14 |
+
class PreTrainedPipeline():
|
15 |
+
def __init__(self, path=""):
|
16 |
+
# Preload all the elements you are going to need at inference.
|
17 |
+
# pseudo:
|
18 |
+
# self.model= load_model(path)
|
19 |
+
|
20 |
+
self.model = AutoModelForCausalLM.from_pretrained(f"RASMUS/Ahma-3B-Instruct-RAG-v0.1", device_map='cuda:0', torch_dtype = torch.bfloat16).eval()
|
21 |
+
self.tokenizer = AutoTokenizer.from_pretrained(f"RASMUS/Ahma-3B-Instruct-RAG-v0.1")
|
22 |
+
self.generation_config = GenerationConfig(
|
23 |
+
pad_token_id = self.tokenizer.eos_token_id,
|
24 |
+
eos_token_id = self.tokenizer.convert_tokens_to_ids("</s>"),
|
25 |
+
)
|
26 |
+
|
27 |
+
def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
28 |
+
"""
|
29 |
+
data args:
|
30 |
+
inputs (:obj: `str` | `PIL.Image` | `np.array`)
|
31 |
+
kwargs
|
32 |
+
Return:
|
33 |
+
A :obj:`list` | `dict`: will be serialized and returned
|
34 |
+
"""
|
35 |
+
context = data.pop("context",None)
|
36 |
+
question = data.pop("question",None)
|
37 |
+
messages = generate_rag_prompt_message(context, question)
|
38 |
+
|
39 |
+
inputs = self.tokenizer(
|
40 |
+
[
|
41 |
+
self.tokenizer.apply_chat_template(messages, tokenize=False)
|
42 |
+
]*1, return_tensors = "pt").to("cuda")
|
43 |
+
|
44 |
+
|
45 |
+
with torch.no_grad():
|
46 |
+
generated_ids = self.model.generate(
|
47 |
+
input_ids=inputs["input_ids"],
|
48 |
+
attention_mask=inputs["attention_mask"],
|
49 |
+
generation_config=self.generation_config, **{
|
50 |
+
"temperature": 0.1,
|
51 |
+
"penalty_alpha": 0.6,
|
52 |
+
"min_p": 0.5,
|
53 |
+
"do_sample": True,
|
54 |
+
"repetition_penalty": 1.28,
|
55 |
+
"min_length": 10,
|
56 |
+
"max_new_tokens": 250
|
57 |
+
})
|
58 |
+
|
59 |
+
generated_text = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True)[0]
|
60 |
+
try:
|
61 |
+
generated_answer = generated_text.split('[/INST]')[1].strip()
|
62 |
+
return json.dumps({"answer": generated_answer})
|
63 |
+
except Exception as e:
|
64 |
+
return json.dumps({"answer": str(e)})
|