Ozgur98 commited on
Commit
7a42e65
1 Parent(s): 02a3e01

Update handler.py

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