ksee commited on
Commit
6f3a73d
1 Parent(s): 7916b6c

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +36 -0
handler.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ from peft import PeftConfig, PeftModel
3
+ import torch.cuda
4
+
5
+ device = "cuda" if torch.cuda.is_available() else "cpu"
6
+
7
+ class EndpointHandler():
8
+ def __init__(self, path=""):
9
+ config = PeftConfig.from_pretrained(path)
10
+ model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path, load_in_8bit=True, device_map='auto')
11
+ self.tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
12
+ # Load the Lora model
13
+ self.model = PeftModel.from_pretrained(model, path)
14
+
15
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
16
+ """
17
+ Args:
18
+ data (Dict): The payload with the text prompt
19
+ and generation parameters.
20
+ """
21
+ # Get inputs
22
+ prompt = data.pop("inputs", None)
23
+ parameters = data.pop("parameters", None)
24
+ if prompt is None:
25
+ raise ValueError("Missing prompt.")
26
+ # Preprocess
27
+ input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(device)
28
+ # Forward
29
+ if parameters is not None:
30
+ output = self.model.generate(input_ids=input_ids, **parameters)
31
+ else:
32
+ output = self.model.generate(input_ids=input_ids)
33
+ # Postprocess
34
+ prediction = self.tokenizer.decode(output[0])
35
+ return {"generated_text": prediction}
36
+