shibing624 commited on
Commit
7af717c
1 Parent(s): ee443b3

Upload handler.py

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