maxmnd commited on
Commit
14280bb
·
verified ·
1 Parent(s): 8a4f3b8

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +85 -0
handler.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
3
+ import torch
4
+
5
+
6
+
7
+ class HuggingFaceHandler:
8
+ def init(self, model_dir: str, task: str):
9
+ """
10
+ Initialize the HuggingFaceHandler with the model directory and task.
11
+ This loads the model and tokenizer.
12
+ """
13
+ self.model_dir = model_dir
14
+ self.task = task
15
+
16
+
17
+
18
+ # Load the model and tokenizer without specifying a device
19
+ self.pipeline = self.get_pipeline()
20
+
21
+
22
+
23
+ def get_pipeline(self):
24
+ """
25
+ Loads the model and tokenizer and sets up the Hugging Face pipeline.
26
+ Let accelerate handle device placement, and remove any device argument.
27
+ """
28
+ try:
29
+ # Load the tokenizer and model from the specified directory
30
+ tokenizer = AutoTokenizer.from_pretrained(self.model_dir)
31
+ model = AutoModelForSeq2SeqLM.from_pretrained(self.model_dir)
32
+
33
+
34
+
35
+ # Create the Hugging Face pipeline (without specifying device)
36
+ hf_pipeline = pipeline(task=self.task, model=model, tokenizer=tokenizer)
37
+ return hf_pipeline
38
+ except Exception as e:
39
+ raise RuntimeError(f"Error loading model and tokenizer: {str(e)}")
40
+
41
+
42
+
43
+ def predict(self, inputs: str) -> str:
44
+ """
45
+ Make predictions using the pipeline.
46
+ :param inputs: Text input for prediction
47
+ :return: Generated text or task-specific output
48
+ """
49
+ try:
50
+ # Pass the input text to the pipeline and generate the output
51
+ result = self.pipeline(inputs)
52
+ return result
53
+ except Exception as e:
54
+ raise RuntimeError(f"Error during inference: {str(e)}")
55
+
56
+
57
+
58
+ def get_inference_handler_either_custom_or_default_handler(model_dir: str, task: str):
59
+ """
60
+ Helper function to return the handler instance.
61
+ """
62
+ return HuggingFaceHandler(model_dir=model_dir, task=task)
63
+
64
+
65
+
66
+ # Example of usage
67
+ if name == "__main__":
68
+ model_directory = os.getenv("MODEL_DIR", "maxmnd/fine_tuned")
69
+ task_type = os.getenv("TASK", "text-generation")
70
+
71
+
72
+
73
+ # Instantiate the handler
74
+ handler = get_inference_handler_either_custom_or_default_handler(model_directory, task_type)
75
+
76
+
77
+
78
+ # Example input text
79
+ input_text = "What is the capital of France?"
80
+
81
+
82
+
83
+ # Perform inference
84
+ output = handler.predict(input_text)
85
+ print("Generated Output:", output)