ammarnasr commited on
Commit
c8c5bab
1 Parent(s): 2733247

create handler

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
+ from typing import Any, Dict
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
+
16
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
17
+ """
18
+ Args:
19
+ data (Dict): The payload with the text prompt
20
+ and generation parameters.
21
+ """
22
+ # Get inputs
23
+ prompt = data.pop("inputs", None)
24
+ parameters = data.pop("parameters", None)
25
+ if prompt is None:
26
+ raise ValueError("Missing prompt.")
27
+ # Preprocess
28
+ input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids.to(device)
29
+ # Forward
30
+ if parameters is not None:
31
+ output = self.model.generate(input_ids=input_ids, **parameters)
32
+ else:
33
+ output = self.model.generate(input_ids=input_ids)
34
+ # Postprocess
35
+ prediction = self.tokenizer.decode(output[0])
36
+ return {"generated_text": prediction}