luxmorocco commited on
Commit
ce50fe0
1 Parent(s): 99ca5b3

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +83 -0
handler.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3
+ from peft import PeftModel, PeftConfig
4
+ import torch
5
+ import time
6
+
7
+ class EndpointHandler:
8
+ def __init__(self, path="luxmorocco/qiyas-falcon-7b"):
9
+ # load the model
10
+ config = PeftConfig.from_pretrained(path)
11
+
12
+ bnb_config = BitsAndBytesConfig(
13
+ load_in_4bit=True,
14
+ bnb_4bit_use_double_quant=True,
15
+ bnb_4bit_quant_type="nf4",
16
+ bnb_4bit_compute_dtype=torch.float16,
17
+ )
18
+
19
+ self.model = AutoModelForCausalLM.from_pretrained(
20
+ config.base_model_name_or_path,
21
+ return_dict=True,
22
+ load_in_4bit=True,
23
+ device_map={"":0},
24
+ trust_remote_code=True,
25
+ quantization_config=bnb_config,
26
+ )
27
+
28
+ self.tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
29
+ self.tokenizer.pad_token = self.tokenizer.eos_token
30
+
31
+ self.model = PeftModel.from_pretrained(self.model, path)
32
+
33
+ def __call__(self, data: Any) -> Dict[str, Any]:
34
+ """
35
+ Args:
36
+ inputs :obj:`list`:. The object should be like {"context": "some word", "question": "some word"} containing:
37
+ - "context":
38
+ - "question":
39
+ Return:
40
+ A :obj:`list`:. The object returned should be like {"answer": "some word", time: "..."} containing:
41
+ - "answer": answer the question based on the context
42
+ - "time": the time run predict
43
+ """
44
+ inputs = data.pop("inputs", data)
45
+ context = inputs.pop("context", inputs)
46
+ question = inputs.pop("question", inputs)
47
+
48
+ prompt = f"""Answer the question based on the context below. If the question cannot be answered using the information provided answer with 'No answer'. Stop response if end.
49
+ >>TITLE<<: Flawless answer.
50
+ >>CONTEXT<<: {context}
51
+ >>QUESTION<<: {question}
52
+ >>ANSWER<<:
53
+ """.strip()
54
+
55
+ batch = self.tokenizer(
56
+ prompt,
57
+ padding=True,
58
+ truncation=True,
59
+ return_tensors='pt'
60
+ )
61
+ batch = batch.to('cuda:0')
62
+
63
+ generation_config = self.model.generation_config
64
+ generation_config.top_p = 0.7
65
+ generation_config.temperature = 0.7
66
+ generation_config.max_new_tokens = 256
67
+ generation_config.num_return_sequences = 1
68
+ generation_config.pad_token_id = self.tokenizer.eos_token_id
69
+ generation_config.eos_token_id = self.tokenizer.eos_token_id
70
+
71
+ start = time.time()
72
+ with torch.cuda.amp.autocast():
73
+ output_tokens = self.model.generate(
74
+ input_ids = batch.input_ids,
75
+ generation_config=generation_config,
76
+ )
77
+ end = time.time()
78
+
79
+ generated_text = self.tokenizer.decode(output_tokens[0])
80
+
81
+ prediction = {'answer': generated_text.split('>>END<<')[0].split('>>ANSWER<<:')[1].strip(), 'time': f"{(end-start):.2f} s"}
82
+
83
+ return prediction