codys12 commited on
Commit
d2659b8
·
1 Parent(s): 6079676

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +104 -0
handler.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any
2
+ import logging
3
+
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from peft import PeftConfig, PeftModel
6
+ import torch.cuda
7
+
8
+
9
+ LOGGER = logging.getLogger(__name__)
10
+ logging.basicConfig(level=logging.INFO)
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+
13
+
14
+ class EndpointHandler():
15
+ def __init__(self, path=""):
16
+ config = PeftConfig.from_pretrained(path)
17
+ model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, load_in_8bit=True, device_map='auto')
18
+ self.tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
19
+ # Load the Lora model
20
+ self.model = PeftModel.from_pretrained(model, path)
21
+
22
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
23
+ LOGGER.info(f"Received data: {data}")
24
+ # Get inputs
25
+ # Extract required parameters from data
26
+ message = data.get("message")
27
+ chat_history = data.get("chat_history", [])
28
+ system_prompt = data.get("system_prompt", "")
29
+
30
+ # Extract optional parameters for the generate function logic
31
+ instruction = data.get("instruction")
32
+ conclusions = data.get("conclusions")
33
+ context = data.get("context")
34
+
35
+ # Optional parameters with default values
36
+ max_new_tokens = data.get("max_new_tokens", 1024)
37
+ temperature = data.get("temperature", 0.6)
38
+ top_p = data.get("top_p", 0.9)
39
+ top_k = data.get("top_k", 50)
40
+ repetition_penalty = data.get("repetition_penalty", 1.2)
41
+
42
+ if message is None or system_prompt is None:
43
+ raise ValueError("Missing required parameters.")
44
+
45
+ # Call the generate function
46
+ output = generate(
47
+ message=message,
48
+ chat_history=chat_history,
49
+ system_prompt=system_prompt,
50
+ instruction=instruction,
51
+ conclusions=conclusions,
52
+ context=context
53
+ max_new_tokens=max_new_tokens,
54
+ temperature=temperature,
55
+ top_p=top_p,
56
+ top_k=top_k,
57
+ repetition_penalty=repetition_penalty
58
+ )
59
+
60
+ # Postprocess
61
+ prediction = self.tokenizer.decode(output[0])
62
+ LOGGER.info(f"Generated text: {prediction}")
63
+ return {"generated_text": prediction}
64
+
65
+ def generate(
66
+ message: str,
67
+ chat_history: list[tuple[str, str]],
68
+ system_prompt: str = None,
69
+ instruction: str = None,
70
+ conclusions: list[tuple[str, str]] = None,
71
+ context: list[str] = None,
72
+ max_new_tokens: int = 1024,
73
+ temperature: float = 0.6,
74
+ top_p: float = 0.9,
75
+ top_k: int = 50,
76
+ repetition_penalty: float = 1.2,
77
+ ) -> Iterator[str]:
78
+
79
+ # Check if the system_prompt is provided, else construct it from instruction, conclusions, and context
80
+ if system_prompt is None and instruction is not None and conclusions is not None and context is not None:
81
+ system_prompt = "Instruction: {}\nConclusions:\n".format(instruction)
82
+ for idx, (conclusion, conclusion_key) in enumerate(conclusions):
83
+ system_prompt += "{}: {}\n".format(conclusion_key, conclusion)
84
+ system_prompt += "\nContext:\n"
85
+ for idx, ctx in enumerate(context):
86
+ system_prompt += "{}: [{}]\n".format(ctx, idx + 1)
87
+
88
+ # Construct conversation history
89
+ conversation = [{"role": "system", "content": system_prompt}]
90
+ for user, assistant in chat_history:
91
+ if user is not None:
92
+ conversation.extend([{"role": "user", "content": user}])
93
+ conversation.extend([{"role": "assistant", "content": assistant}])
94
+ conversation.append({"role": "user", "content": message})
95
+
96
+ # Tokenize and process the conversation
97
+ input_ids = self.tokenizer.apply_chat_template(conversation, return_tensors="pt")
98
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
99
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
100
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
101
+ input_ids = input_ids.to(model.device)
102
+
103
+ # Generate the response
104
+ return model.generate(input_ids.input_ids, max_new_tokens=max_new_tokens)