orion-penner HF staff commited on
Commit
530ae6b
1 Parent(s): e70200e

Created handler.py

Browse files
Files changed (1) hide show
  1. handler.py +36 -0
handler.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import sys
3
+
4
+ def install(package):
5
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package])
6
+
7
+ # Additional module required to load the model.
8
+ install("einops")
9
+
10
+ import torch
11
+ from typing import Dict, List, Any
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
13
+
14
+ # get dtype
15
+ dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] == 8 else torch.float16
16
+
17
+
18
+ class EndpointHandler:
19
+ def __init__(self, path=""):
20
+ # load the model
21
+ tokenizer = AutoTokenizer.from_pretrained(path,trust_remote_code=True)
22
+ model = AutoModelForCausalLM.from_pretrained(path, device_map="auto",torch_dtype=dtype, trust_remote_code=True)
23
+ # create inference pipeline
24
+ self.pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer)
25
+
26
+ def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
27
+ inputs = data.pop("inputs", data)
28
+ parameters = data.pop("parameters", None)
29
+
30
+ # pass inputs with all kwargs in data
31
+ if parameters is not None:
32
+ prediction = self.pipeline(inputs, **parameters)
33
+ else:
34
+ prediction = self.pipeline(inputs)
35
+ # postprocess the prediction
36
+ return prediction