JonLoRA commited on
Commit
8d554a1
·
verified ·
1 Parent(s): dfe9a84

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +70 -0
handler.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any, List
2
+ import torch
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+
5
+ class EndpointHandler:
6
+ def __init__(self, path=""):
7
+ """Initialize the model and tokenizer.
8
+
9
+ Args:
10
+ path (str): Path to the model directory. Defaults to empty string.
11
+ """
12
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ self.model = AutoModelForCausalLM.from_pretrained(
14
+ path or "merged",
15
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
16
+ device_map="auto"
17
+ )
18
+ self.tokenizer = AutoTokenizer.from_pretrained(path or "merged")
19
+
20
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
21
+ """Handle inference requests.
22
+
23
+ Args:
24
+ data (Dict[str, Any]): The input data containing:
25
+ - instruction (str): The instruction for the model
26
+ - input (str, optional): Additional input text
27
+ - max_new_tokens (int, optional): Maximum number of tokens to generate. Defaults to 512
28
+ - temperature (float, optional): Sampling temperature. Defaults to 0.7
29
+
30
+ Returns:
31
+ Dict[str, Any]: The model's response containing:
32
+ - response (str): The generated text
33
+ """
34
+ # Extract parameters from the request
35
+ instruction = data.get("instruction", "")
36
+ input_text = data.get("input", "")
37
+ max_new_tokens = data.get("max_new_tokens", 512)
38
+ temperature = data.get("temperature", 0.7)
39
+
40
+ # Create prompt
41
+ prompt = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
42
+
43
+ ### Instruction:
44
+ {instruction}"""
45
+
46
+ if input_text:
47
+ prompt += f"""
48
+
49
+ ### Input:
50
+ {input_text}"""
51
+
52
+ prompt += """
53
+
54
+ ### Response:"""
55
+
56
+ # Generate response
57
+ inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
58
+ outputs = self.model.generate(
59
+ **inputs,
60
+ max_new_tokens=max_new_tokens,
61
+ temperature=temperature,
62
+ do_sample=True,
63
+ pad_token_id=self.tokenizer.eos_token_id
64
+ )
65
+
66
+ # Decode and extract response
67
+ full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
68
+ response = full_response.split("### Response:")[-1].strip()
69
+
70
+ return {"response": response}